Add root possibility

This commit is contained in:
ccocchi 2012-03-22 11:24:55 +01:00
parent dfbe769a91
commit 35ba212214
5 changed files with 25 additions and 10 deletions

View File

@ -77,16 +77,16 @@ module RablFastJson
@template.data, @template.root_name = data, name
end
def method_missing(name, *args, &block)
@context.respond_to?(name) ? @context.send(name, *args, &block) : super
end
protected
def extract_data_and_name(name_or_data)
case name_or_data
when Symbol
[name_or_data, name_or_data]
if name_or_data.to_s.start_with?('@')
[name_or_data, nil]
else
[name_or_data, name_or_data]
end
when Hash
name_or_data.first
else

View File

@ -4,7 +4,7 @@ module RablFastJson
cattr_accessor :default_format
self.default_format = 'application/json'
def self.call(template)
def self.call(template)
%{
RablFastJson::Library.instance.
get_rendered_template(#{template.source.inspect}, self)

View File

@ -16,12 +16,13 @@ module RablFastJson
compiled_template = get_compiled_template(path, source, context)
compiled_template.context = context
ActiveSupport::JSON.encode(compiled_template.render)
body = compiled_template.render
ActiveSupport::JSON.encode(compiled_template.has_root_name? ? { compiled_template.root_name => body } : body)
end
def get_compiled_template(path, source, context)
@cached_templates[path] ||= Compiler.new(context).compile_source(source)
# @cached_templates[path] ||=
Compiler.new(context).compile_source(source)
end
def get(path, context)

View File

@ -2,7 +2,7 @@ module RablFastJson
class Railtie < Rails::Railtie
initializer "rabl.initialize" do |app|
ActiveSupport.on_load(:action_view) do
ActionView::Template.register_template_handler :rabl2, RablFastJson::Handlers::Rabl
ActionView::Template.register_template_handler :rabl, RablFastJson::Handlers::Rabl
end
end
end

View File

@ -18,6 +18,20 @@ module RablFastJson
instance_variable_set("@#{k}", v) unless k.start_with?('_') || k == @data
}
end
def has_root_name?
!@root_name.nil?
end
def method_missing(name, *args, &block)
@context.respond_to?(name) ? @context.send(name, *args, &block) : super
end
def partial(template_path, options = {})
raise "No object was given to partial" if options[:object].blank?
template = Library.instance.get(template_path, @context)
template.render_resource(options[:object])
end
def render
get_object_from_context