rabl-rails/lib/rabl-fast-json/template.rb

57 lines
1.5 KiB
Ruby
Raw Normal View History

2012-02-22 18:14:00 +00:00
module RablFastJson
class CompiledTemplate
2012-02-27 13:49:34 +00:00
attr_accessor :source, :data, :root_name, :context
2012-02-22 18:14:00 +00:00
2012-02-27 13:49:34 +00:00
delegate :[], :[]=, :merge!, :to => :source
2012-02-22 18:14:00 +00:00
def initialize
@source = {}
end
2012-02-27 13:49:34 +00:00
def get_object_from_assigns
@object = @context.instance_variable_get(@data)
end
def render
get_object_from_assigns
@object.respond_to?(:each) ? render_collection : render_resource
end
def render_resource(data = nil, source = nil)
data ||= @object
source ||= @source
2012-02-27 16:25:06 +00:00
source.inject({}) { |output, current|
key, value = current
2012-03-02 10:32:11 +00:00
2012-02-27 13:49:34 +00:00
out = case value
when Symbol
data.send(value) # attributes
when Proc
value.call(data) # node
when Hash
2012-03-02 10:32:11 +00:00
current_value = value.dup
data_symbol = current_value.delete(:_data)
object = data_symbol.nil? ? data : data_symbol.to_s.start_with?('@') ? @context.instance_variable_get(data_symbol) : data.send(data_symbol)
2012-02-27 13:49:34 +00:00
if key.to_s.start_with?('_') # glue
2012-03-02 10:32:11 +00:00
current_value.each_pair { |k, v|
2012-02-27 13:49:34 +00:00
output[k] = object.send(v)
}
2012-02-27 16:25:06 +00:00
next output
2012-02-27 13:49:34 +00:00
else # child
2012-03-02 10:32:11 +00:00
object.respond_to?(:each) ? render_collection(object, current_value) : render_resource(object, current_value)
2012-02-27 13:49:34 +00:00
end
end
output[key] = out
2012-02-27 16:25:06 +00:00
output
2012-02-27 13:49:34 +00:00
}
end
def render_collection(collection = nil, source = nil)
collection ||= @object
2012-02-27 16:25:06 +00:00
collection.inject([]) { |output, o| output << render_resource(o, source) }
2012-02-27 13:49:34 +00:00
end
2012-02-22 18:14:00 +00:00
end
end