ccocchi / rabl-rails

Rails 4.2+ templating system with JSON, XML and Plist support.
MIT License
209 stars 51 forks source link

rabl-rails for rails-5-api? #86

Closed saravanabalagi closed 6 years ago

saravanabalagi commented 7 years ago

Is there a way, I can make this gem work with rails-api? More here: stackoverflow post

render json renders from as_json and how do I link it with app/views?

ccocchi commented 6 years ago

You should add the following two lines to your ApplicationController

include ActionView::Rendering
append_view_path "#{Rails.root}/app/views"
jr180180 commented 6 years ago

We had an issue with the RABL templates not rendering after changing our API base controller inheritance from ActionController::Base to ActionController::API in Rails 5.

I found https://github.com/nesquena/rabl/issues/687 and added the jbuilder gem without the includes mentioned above and everything rendered correctly again.

ccocchi commented 6 years ago

If you look at the code from jbuilder you can see that it does the include for you :)

       if Rails::VERSION::MAJOR >= 5
        module ::ActionController
          module ApiRendering
            include ActionView::Rendering
          end
        end

        ActiveSupport.on_load :action_controller do
          if self == ActionController::API
            include ActionController::Helpers
            include ActionController::ImplicitRender
          end
        end
      end
jr180180 commented 6 years ago

@ccocchi , Major thanks for pointing that out! 👍 👍

Now I don't have to add yet another dependency to the Gemfile. 😄

I wasn't able to get it working with the following in our BaseController:

include ActionView::Rendering
append_view_path "#{Rails.root}/app/views"

However, I was able to get the RABL templates working again by including the Rendering module like jbuilder does.

For example:

# Outside of the base_controller
module ActionController::ApiRendering; include ActionView::Rendering; end

# Inside of the base_controller
class BaseController < ActionController::API
 include ActionController::ImplicitRender
end
ccocchi commented 6 years ago

Yeah, order of inclusion matters here so better to use what jbuilder does ;)