From c33df6fec5d97e0a29214de6d189713a2d413be6 Mon Sep 17 00:00:00 2001 From: Sebastian Edwards Date: Wed, 19 Sep 2012 22:37:35 +1200 Subject: [PATCH] Allow created objects to be decorated via a callable option. --- lib/cocoon/view_helpers.rb | 8 +++++++- spec/cocoon_spec.rb | 6 ++++++ spec/dummy/app/decorators/comment_decorator.rb | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 spec/dummy/app/decorators/comment_decorator.rb diff --git a/lib/cocoon/view_helpers.rb b/lib/cocoon/view_helpers.rb index aa12a63..7b66e7c 100644 --- a/lib/cocoon/view_helpers.rb +++ b/lib/cocoon/view_helpers.rb @@ -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 ) diff --git a/spec/cocoon_spec.rb b/spec/cocoon_spec.rb index 5881bd6..355d650 100644 --- a/spec/cocoon_spec.rb +++ b/spec/cocoon_spec.rb @@ -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 == 'add something' 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 diff --git a/spec/dummy/app/decorators/comment_decorator.rb b/spec/dummy/app/decorators/comment_decorator.rb new file mode 100644 index 0000000..bb49c17 --- /dev/null +++ b/spec/dummy/app/decorators/comment_decorator.rb @@ -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