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)