Skip to content

Commit

Permalink
Added supermodel attributes to non-persisted entities
Browse files Browse the repository at this point in the history
  • Loading branch information
felipeclopes committed Mar 7, 2017
1 parent 1acf8ec commit a3d8bf0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 28 deletions.
4 changes: 2 additions & 2 deletions lib/active_record/acts_as/instance_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ def write_store_attribute(store_attribute, key, value)
private :write_attribute, :write_store_attribute

def attributes
acting_as_persisted? ? acting_as.attributes.except(acting_as_reflection.type, acting_as_reflection.foreign_key).merge(super) : super
acting_as.nil? ? super : acting_as.attributes.except(acting_as_reflection.type, acting_as_reflection.foreign_key).merge(super)
end

def attribute_names
acting_as_persisted? ? super | (acting_as.attribute_names - [acting_as_reflection.type, acting_as_reflection.foreign_key]) : super
acting_as.nil? ? super : super | (acting_as.attribute_names - [acting_as_reflection.type, acting_as_reflection.foreign_key])
end

def has_attribute?(attr_name, as_original_class = false)
Expand Down
60 changes: 34 additions & 26 deletions spec/acts_as_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -347,32 +347,40 @@
end

context "includes supermodel attributes in .to_json response" do
it "unless the submodel instance association doesn't exist" do
expect(JSON.parse(isolated_pen.to_json)).to eq(JSON.parse('''
{
"id": null,
"color": "red",
"pen_collection_id": null
}
'''))
end

it "if the submodel instance association exists" do
p = Product.new(name: 'Test Pen', price: 0.8, actable: pen)
p.save
expect(JSON.parse(pen.to_json)).to eq(JSON.parse('''
{
"id": '+ pen.id.to_s + ',
"name": "pen",
"price": 0.8,
"store_id": null,
"pen_collection_id": null,
"settings": {},
"color": "red",
"created_at": ' + pen.created_at.to_json + ',
"updated_at": ' + pen.updated_at.to_json + '
}
'''))
context "if the submodel instance association " do
it "doesn't exist" do
expect(JSON.parse(pen.to_json)).to eq(JSON.parse('''
{
"id": null,
"name": "pen",
"price": 0.8,
"store_id": null,
"pen_collection_id": null,
"settings": {},
"color": "red",
"created_at": null,
"updated_at": null
}
'''))
end

it "exists" do
p = Product.new(name: 'Test Pen', price: 0.8, actable: pen)
p.save
expect(JSON.parse(pen.to_json)).to eq(JSON.parse('''
{
"id": '+ pen.id.to_s + ',
"name": "pen",
"price": 0.8,
"store_id": null,
"pen_collection_id": null,
"settings": {},
"color": "red",
"created_at": ' + pen.created_at.to_json + ',
"updated_at": ' + pen.updated_at.to_json + '
}
'''))
end
end
end

Expand Down

0 comments on commit a3d8bf0

Please sign in to comment.