Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

How to conditionally render template in Grape resources?

Suppose you need to conditionally render some template in a given endpoint of a Grape resource. There is a env data in Grape::API class that represents Rack environment of the request. env is just a simple Ruby hash and we can pass the template name to it’s api.tilt.template key to render that template:

env['api.tilt.template'] = 'foo/bar.json'

Then let’s define a render method in Base resourсe:

class Base < Grape::API
  def self.inherited(subclass)
    super

    subclass.instance_eval do
      helpers do
        def render(template_name)
          env['api.tilt.template'] = template_name
        end
      end
    end
  end
end

Now we can use it in the following way:

class ContactsResource < Base
  desc 'Create contact', http_codes: [[201, 'Created']]

  post '/contacts' do
    contact = Contact.new(params[:contact])

    if contact.save
      render 'v1/contacts/show.json'
    else
      error!({ errors: contact.errors.full_messages }, 422)
    end
  end
end
Looking for help? JetRockets has been an leader in Ruby on Rails since 2012. Rails is a core skill for each developer at JetRockets and we'd love to take a look at your project. Contact us and find out how we can help you.