Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

Sometimes you want to support both GET and POST in a Grape API.

If you want to support GET you would write something like get [path] do. If you want to support POST you would write post [path] do. What are those get and post methods anyway? The answer is in Grape’s api.rb.

def get(paths = ['/'], options = {}, &block); route('GET', paths, options, &block) end
def post(paths = ['/'], options = {}, &block); route('POST', paths, options, &block) end
def put(paths = ['/'], options = {}, &block); route('PUT', paths, options, &block) end
def head(paths = ['/'], options = {}, &block); route('HEAD', paths, options, &block) end
def delete(paths = ['/'], options = {}, &block); route('DELETE', paths, options, &block) end

These call route, which starts as follows.

def route(methods, paths = ['/'], route_options = {}, &block)
  methods = Array(methods)
  ...
end

The Array construct will take anything and make it into an array, unless it’s already one. Which means that we can pass an array of methods to route. This is definitely part of Ruby magic, a C# or Java developer would strangle you for accepting object as a parameter and then transforming it into [object] _– but this is completely kosher in Ruby. But I digress, in order to route multiple methods for a single API we can invoke _route directly instead of get or post.

route ['GET', 'POST'], "foo/bar" do
  # API code goes here
end