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