Allow created objects to be decorated via a callable option.

This commit is contained in:
Sebastian Edwards 2012-09-19 22:37:35 +12:00
parent c2a0be513d
commit c33df6fec5
3 changed files with 30 additions and 1 deletions

View File

@ -67,12 +67,18 @@ module Cocoon
render_options = html_options.delete(:render_options)
render_options ||= {}
override_partial = html_options.delete(:partial)
wrap_object = html_options.delete(:wrap_object)
html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ')
html_options[:'data-association'] = association.to_s.singularize
html_options[:'data-associations'] = association.to_s.pluralize
new_object = create_object(f, association)
if wrap_object.respond_to?(:call)
new_object = wrap_object.call(create_object(f, association))
else
new_object = create_object(f, association)
end
html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, render_options, override_partial)).html_safe
link_to(name, '#', html_options )

View File

@ -35,6 +35,12 @@ describe Cocoon do
result = @tester.link_to_add_association('add something', @form_obj, :comments, :partial => "shared/partial")
result.to_s.should == '<a href="#" class="add_fields" data-association-insertion-template="partiallll" data-association="comment" data-associations="comments">add something</a>'
end
it "gives an opportunity to wrap/decorate created objects" do
@tester.unstub(:render_association)
@tester.should_receive(:render_association).with(anything(), anything(), kind_of(CommentDecorator), anything(), anything()).and_return('partiallll')
@tester.link_to_add_association('add something', @form_obj, :comments, :wrap_object => Proc.new {|comment| CommentDecorator.new(comment) })
end
end
context "with a block" do

View File

@ -0,0 +1,17 @@
class CommentDecorator
def initialize(comment)
@comment = comment
end
def formatted_created_at
@comment.created_at.to_formatted_s(:short)
end
def method_missing(method_sym, *args)
if @comment.respond_to?(method_sym)
@comment.send(method_sym, *args)
else
super
end
end
end