From 3c93153a31577636507b9689bd11394312c1f6cb Mon Sep 17 00:00:00 2001 From: Gavin Joyce Date: Wed, 4 Feb 2015 21:30:05 +0000 Subject: [PATCH] models can now be hashes --- lib/restpack_serializer/serializable/attributes.rb | 6 +++++- spec/serializable/attributes_spec.rb | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/restpack_serializer/serializable/attributes.rb b/lib/restpack_serializer/serializable/attributes.rb index 8bb19ec..2e962f4 100644 --- a/lib/restpack_serializer/serializable/attributes.rb +++ b/lib/restpack_serializer/serializable/attributes.rb @@ -38,7 +38,11 @@ def define_attribute_method(name) unless method_defined?(name) define_method name do value = self.default_href if name == :href - value ||= @model.send(name) + if @model.is_a?(Hash) + value ||= @model[name] || @model[name.to_s] + else + value ||= @model.send(name) + end value = value.to_s if name == :id value end diff --git a/spec/serializable/attributes_spec.rb b/spec/serializable/attributes_spec.rb index b0f9556..37381ea 100644 --- a/spec/serializable/attributes_spec.rb +++ b/spec/serializable/attributes_spec.rb @@ -33,4 +33,15 @@ class CustomSerializer expect(as_json[:gonzaga]).to eq('is a school') end end + + describe "model as a hash" do + let(:model) { { a: 'A', 'b' => 'B' } } + + subject(:as_json) { CustomSerializer.as_json(model, include_gonzaga?: false) } + + it 'uses the transform method on the model attribute' do + expect(as_json[:a]).to eq('A') + expect(as_json[:b]).to eq('B') + end + end end