Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions lib/store_attribute/active_record/store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,11 @@ def store_attribute(store_name, name, type = :value, prefix: nil, suffix: nil, *

_define_store_attribute(store_name) if !_local_typed_stored_attributes? ||
_local_typed_stored_attributes[store_name][:types].empty? ||
# Defaults owner has changed, we must decorate the attribute to correctly propagate the defaults
(
options.key?(:default) && _local_typed_stored_attributes[store_name][:owner] != self
)
# Owner has changed (e.g., subclass adding to inherited store),
# we must re-decorate the attribute to correctly set up type casting and defaults
_local_typed_stored_attributes[store_name][:owner] != self

_local_typed_stored_attributes[store_name][:owner] = self if options.key?(:default) || !_local_typed_stored_attributes?
_local_typed_stored_attributes[store_name][:owner] = self if !_local_typed_stored_attributes? || _local_typed_stored_attributes[store_name][:owner] != self
_local_typed_stored_attributes[store_name][:types][name] = [type, options]

# In case #decorate_attribute has already been invoked, add new type information right away
Expand Down
26 changes: 26 additions & 0 deletions spec/cases/store_attribute_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,32 @@
expect(jamie).to be_active
expect(jamie.salary).to eq 100
end

it "typecasts inherited typed store attributes without defaults on reload" do
subclass = Class.new(User) do
store_attribute :jparams, :amount, :decimal, precision: 15, scale: 2
end

record = subclass.create!(jparams: {"amount" => "12345.67"})
record.reload

expect(record.amount).to eq BigDecimal("12345.67")
expect(record.jparams["amount"]).to eq BigDecimal("12345.67")
end

it "typecasts typed store attributes without defaults on reload" do
klass = Class.new(ActiveRecord::Base) do
self.table_name = "users"

store_attribute :jparams, :amount, :decimal, precision: 15, scale: 2
end

record = klass.create!(jparams: {"amount" => "12345.67"})
record.reload

expect(record.amount).to eq BigDecimal("12345.67")
expect(record.jparams["amount"]).to eq BigDecimal("12345.67")
end
end

context "custom types" do
Expand Down