lib/gon/rabl.rb in gon-4.0.3 vs lib/gon/rabl.rb in gon-4.1.0

- old
+ new

@@ -1,20 +1,26 @@ require 'action_view' -require 'rabl' +begin + require 'rabl' # use rabl gem if it's available +rescue LoadError +end +begin + require 'rabl-rails' # use rabl-rails gem if it's available +rescue LoadError +end + class Gon module Rabl class << self def handler(args, global = false) options = parse_options_from args, global if global && !options[:template] raise 'You should provide :template when use rabl with global variables' end - include_helpers - data = parse_rabl \ Gon::Base.get_template_path(options, 'rabl'), Gon::Base.get_controller(options), options[:locals] @@ -22,15 +28,36 @@ end private def parse_rabl(rabl_path, controller, locals) + if defined? ::Rabl + parse_with_rabl rabl_path, controller, locals + elsif defined? ::RablRails + parse_with_rabl_rails rabl_path, controller, locals + else + raise 'rabl or rabl-rails must be required in order to use gon.rabl' + end + end + + def parse_with_rabl(rabl_path, controller, locals) locals ||= {} source = File.read(rabl_path) + include_helpers rabl_engine = ::Rabl::Engine.new(source, :format => 'json') - output = rabl_engine.render(controller, locals) + JSON.parse(output) + end + 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 def parse_options_from(args, global) if old_api? args