draper icon indicating copy to clipboard operation
draper copied to clipboard

Addition of Draper Gem causes empty string output in ActionController::API requests

Open synth opened this issue 6 years ago • 3 comments

When we add gem 'draper' to our Gemfile in our Rails 5.0.x project, it breaks our ActionController::API requests by causing an empty string to be returned. I believe this is due to our use of the responders gem as well.

We see the debugger hit the following:

# .rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/responders-2.4.0/lib/action_controller/responder.rb
  184:     def to_format
   185:       if !get? && has_errors? && !response_overridden?
   186:         display_errors
   187:       elsif has_view_rendering? || response_overridden?
=> 188:         default_render
   189:       else
   190:         api_behavior
   191:       end
# .rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/responders-2.4.0/lib/action_controller/responder.rb
   278:     def has_view_rendering?
=> 279:       controller.class.include? ActionView::Rendering
   280:     end

So, has_view_rendering? returns true due to the injection of ActionView::Rendering into the class hierarchy by Draper in the Draper::Compatability::ApiOnly module. This causes the default_render to be called and not the api_behavior which is what we need and see when we don't have the Draper gem in the Gemfile.

The ApiOnly module is run automatically upon gem load to "temporarily" add view_context support to ActionController::API. In the comments it explicitly calls this a "hack" and "temporary solution". If so, there should be a way for developers to opt out of this functionality.

https://github.com/drapergem/draper/blob/aaa06bd2f1e219838b241a5534e7ca513edd1fe2/lib/draper/compatibility/api_only.rb#L1-L23

It seems like a very bad practice to modify class hierarchies just by adding a gem. Is it possible to add a setting to opt out of this behavior - or better, make it opt-in.

PS. Other than this, love the gem.

synth avatar Jul 31 '19 07:07 synth

I ran into this same exact problem with draper 3.1.0

diegous avatar Nov 27 '20 04:11 diegous