ccocchi / rabl-rails

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

New way of format retrieving caused problems with gon gem #69

Closed bsedin closed 7 years ago

bsedin commented 9 years ago

I use responders, gon and gon_responder gems to preload js variables, so with index action I have something like this:

class IvrsController < ApplicationController
  respond_to :html, :json
  def index
    respond_with ivrs, gon: { rabl: { as: :ivrs }}
  end
  ...
end

So I get ivrs collection rendered with gon in html format and plain json in json format. But after 77f894b332ac42a0d4b7e69928c291f40ebae79b:

RENDERER_MAP = {
  'json'  => Renderers::JSON,
  'xml'   => Renderers::XML,
  'ruby'  => Renderers::Hash,
  'plist' => Renderers::PLIST
}.freeze
...
format = view.params[:format] ? view.params[:format].to_s.downcase : 'json'
RENDERER_MAP[format].render(compiled_template, view, locals)

with format html i get exception while trying nil.render(..)

What about fallback to json renderer?

format = view.params[:format] ? view.params[:format].to_s.downcase : 'json'
+ format = 'json' unless RENDERER_MAP.has_key? format
RENDERER_MAP[format].render(compiled_template, view, locals)
ccocchi commented 9 years ago

But why is rabl-rails used when format is HTML? Shouldn't it be rendered by erb (or any others) for example?

With this commit e7276e0c8bc164baf81253ae271204e441283eca, rabl-rails we'll now rely on Rails to determine the format of the response, let me know if if changes something for you.

ccocchi commented 9 years ago

Ok nvm I did not understood what the gon gem was doing. Now that I have, it is because the gem is not setting the format according to the new version. I'll open a PR on the gon gem when I'm decided on how to retrieve the format correctly :laughing:

ccocchi commented 9 years ago

v0.4.1 should fix your issue with gon.

Let me know if that does not work.

bsedin commented 9 years ago

Still doesn't work, but now it fails with pretty error RablRails::Library::UnknownFormat html is not supported in rabl-rails =)

So I took a look at gon gem sources and found that method in https://github.com/gazay/gon/blob/master/lib/gon/rabl.rb:

def parse_with_rabl_rails(rabl_path, controller, locals)
  locals ||= {}
  source = File.read(rabl_path)
  original_formats = controller.formats
  controller.formats = [:json]
  view_context = controller.view_context
  locals.each { |k, v| view_context.assigns[k.to_s] = v }
  output = RablRails::Library.instance.get_rendered_template(source, view_context)
  controller.formats = original_formats
  JSON.parse(output)
end

Seems like gon is trying to cheat rabl-rails' format determination:

controller.formats = [:json]

But since you changed format determination e7276e0c8bc164baf81253ae271204e441283eca gon broke.

Looks like problem on a gon side. I'll open PR there.