ruby-grape / grape-rabl

Use rabl with grape
MIT License
136 stars 29 forks source link

Enable grape-rabl to render correct rabl version of the object #24

Closed rantrix closed 10 years ago

rantrix commented 10 years ago

Add the version to the template file path so that the correct version of the rabl is rendered.

class API::V1::Users < Grape::API
  version 'v1', using: :header, vendor: 'leeo'
  format :json
  formatter :json, Grape::Formatter::Rabl
end

class API::V2::Users < Grape::API
  version 'v2', using: :header, vendor: 'leeo'
  format :json
  formatter :json, Grape::Formatter::Rabl
end

class Application < Rails::Application
    config.middleware.use(Rack::Config) do |env|
        env['api.tilt.root'] = Rails.root.join "app", "views", "api"
    end
end

With that setup, the template path will now contain the env['api.version']. If there isn't a version specified, then the original path will work fine.

I think the specs will have to include these use cases of versioning.

dblock commented 10 years ago

For one, this will break all existing clients. What we want here is probably a way to configure the template path with a lambda that is evaluated every time.

dblock commented 10 years ago

Btw, right now specifying rabl: "v1/user.rabl" as an API parameter would do the trick, right?

rantrix commented 10 years ago

@dblock wow, rabl: "v1/user.rabl" is a pretty good solution to this. Though this solution did make me wonder: why make the user specify which version of the rabl to use when grape is already specifying it? Versioning is a big aspect of Grape and I think that grape-rabl should take this into consideration when it integrates grape and rabl together. What do you think?

If you have some spare time, can you please explain your suggestion of using a lambda? I'd love to understand more. Is the env variable not being reconfigured on every request? I tried using this PR in my current rails app and it seems to be able to deliver the correct version of the rabl file based on the version that was set by the grape::api class. Thank you! =]

dblock commented 10 years ago

Because not everybody maps version to something.rabl. You don't want to impose a directory structure on people's organization of template files that they cannot get out of.

I think I would like to be able to do:

Grape::Rabl.configure do |config|
  config.tilt_root = -> { "#{env['api.version']}/..." }
end