From 94f83a2e0b29d426124a866f9e5d753696af30e9 Mon Sep 17 00:00:00 2001 From: Andrew Haines Date: Thu, 31 Jan 2013 09:28:21 +0000 Subject: [PATCH] Only return attributes implemented by the decorator Closes #444 --- lib/draper/decorator.rb | 8 +++++++- spec/draper/decorator_spec.rb | 9 +++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/draper/decorator.rb b/lib/draper/decorator.rb index 6416519..ad86e83 100755 --- a/lib/draper/decorator.rb +++ b/lib/draper/decorator.rb @@ -187,8 +187,14 @@ module Draper self end + # @return [Hash] the source's attributes, sliced to only include those + # implemented by the decorator. + def attributes + source.attributes.select {|attribute, _| respond_to?(attribute) } + end + # ActiveModel compatibility - delegate :attributes, :to_param, :to_partial_path + delegate :to_param, :to_partial_path # ActiveModel compatibility singleton_class.delegate :model_name, to: :source_class diff --git a/spec/draper/decorator_spec.rb b/spec/draper/decorator_spec.rb index 94cc635..3f49882 100755 --- a/spec/draper/decorator_spec.rb +++ b/spec/draper/decorator_spec.rb @@ -345,6 +345,15 @@ module Draper end end + describe "#attributes" do + it "returns only the source's attributes that are implemented by the decorator" do + decorator = Decorator.new(double(attributes: {foo: "bar", baz: "qux"})) + decorator.stub(:foo) + + expect(decorator.attributes).to eq({foo: "bar"}) + end + end + describe ".model_name" do it "delegates to the source class" do Decorator.stub source_class: double(model_name: :delegated)