Skip to content

Commit

Permalink
Fix serialization for overridden fields.
Browse files Browse the repository at this point in the history
- When a declared field has it's getter overridden, we return the value
  of the overridden method and not of read_attribute.

- Closes #2023.
  • Loading branch information
durran committed May 19, 2012
1 parent 1f7abb0 commit 3d77da7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/mongoid/serialization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def serializable_hash(options = nil)
(attribute_names + method_names).each do |name|
if relations.has_key?(name)
value = send(name)
attrs[name] = value.serializable_hash(options)
elsif attribute_names.include?(name.to_s)
attrs[name] = value ? value.serializable_hash(options) : nil
elsif attribute_names.include?(name) && !fields.has_key?(name)
attrs[name] = read_attribute(name)
else
attrs[name] = send(name)
Expand Down
5 changes: 5 additions & 0 deletions spec/app/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Person
field :security_code
field :reading, :type => Object
field :bson_id, :type => BSON::ObjectId
field :override_me, :type => Integer

index :age
index :addresses
Expand Down Expand Up @@ -147,6 +148,10 @@ def savable?
self.mode != :prevent_save
end

def override_me
read_attribute(:override_me).to_s
end

class << self
def accepted
criteria.where(:terms => true)
Expand Down
15 changes: 15 additions & 0 deletions spec/functional/mongoid/serialization_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@
end
end

context "when the method for a declared field is overridden" do

before do
person.override_me = 1
end

let(:attributes) do
person.serializable_hash
end

it "uses the overridden method" do
attributes["override_me"].should eq("1")
end
end

context "when the model has embedded documents" do

let!(:address) do
Expand Down

0 comments on commit 3d77da7

Please sign in to comment.