lib/jbuilder/jbuilder_template.rb in jbuilder-1.4.2 vs lib/jbuilder/jbuilder_template.rb in jbuilder-1.5.0

- old
+ new

@@ -4,38 +4,76 @@ def initialize(context, *args, &block) @context = context super(*args, &block) end - def partial!(options, locals = {}) - case options + def partial!(name_or_options, locals = {}) + case name_or_options when ::Hash - options[:locals] ||= {} - options[:locals].merge!(:json => self) - @context.render(options.reverse_merge(:handlers => [:jbuilder])) - else # String - @context.render(:partial => options, :locals => locals.merge(:json => self), :handlers => [:jbuilder]) + # partial! partial: 'name', locals: { foo: 'bar' } + options = name_or_options + else + # partial! 'name', foo: 'bar' + options = { :partial => name_or_options, :locals => locals } + as = locals.delete(:as) + options[:as] = as if as.present? + options[:collection] = locals[:collection] end + + _handle_partial_options options end + def array!(collection, *attributes, &block) + options = attributes.extract_options! + + if options.key?(:partial) + partial! options[:partial], options.merge(:collection => collection) + else + super + end + end + # Caches the json constructed within the block passed. Has the same signature as the `cache` helper # method in `ActionView::Helpers::CacheHelper` and so can be used in the same way. # # Example: # # json.cache! ['v1', @person], :expires_in => 10.minutes do # json.extract! @person, :name, :age # end def cache!(key=nil, options={}, &block) - options[:force] = true unless @context.controller.perform_caching - value = ::Rails.cache.fetch(_cache_key(key), options) do - _scope { yield self } - end + if @context.controller.perform_caching + value = ::Rails.cache.fetch(_cache_key(key), options) do + _scope { yield self } + end - _merge(value) + _merge(value) + else + yield + end end protected + def _handle_partial_options(options) + options.reverse_merge!(:locals => {}, :handlers => [:jbuilder]) + collection = options.delete(:collection) + as = options[:as] + + if collection && as + array!(collection) do |member| + options[:locals].merge!(as => member, :collection => collection) + _render_partial options + end + else + _render_partial options + end + end + + def _render_partial(options) + options[:locals].merge!(:json => self) + @context.render options + end + def _cache_key(key) if @context.respond_to?(:cache_fragment_name) # Current compatibility, fragment_name_with_digest is private again and cache_fragment_name # should be used instead. @context.cache_fragment_name(key) \ No newline at end of file