Skip to content

Commit

Permalink
Preserve readonly and strict_loading status on cast
Browse files Browse the repository at this point in the history
  • Loading branch information
martinschaflitzl1 committed Nov 30, 2023
1 parent a379e1d commit 36bd515
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/active_type/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ def cast_record(record, klass, force: false)
casted.instance_variable_set(:@destroyed, record.destroyed?)
# Rails 5.2+
casted.instance_variable_set(:@mutations_from_database, record.instance_variable_get(:@mutations_from_database))
# Rails 6.1+
casted.instance_variable_set(:@strict_loading, record.instance_variable_get(:@strict_loading))
# Rails 7.0+
casted.instance_variable_set(:@strict_loading_mode, record.instance_variable_get(:@strict_loading_mode))
# Rails 1.0+
casted.instance_variable_set(:@readonly, record.instance_variable_get(:@readonly))

# Rails 3.2, 4.2
errors = record.errors
Expand Down
28 changes: 28 additions & 0 deletions spec/active_type/util_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,34 @@ class AssociatedRecord < ActiveRecord::Base
expect(base_record.errors.size).to eq 0
end

it 'preserves the readonly status' do
base_record = UtilSpec::BaseRecord.create!
base_record.readonly!
expect(base_record).to be_readonly
extended_record = ActiveType::Util.cast(base_record, UtilSpec::ExtendedRecord)
expect(extended_record).to be_readonly
end

if ActiveRecord::VERSION::MAJOR >= 7 || (ActiveRecord::VERSION::MAJOR == 6 && ActiveRecord::VERSION::MINOR >= 1)
it 'preserves the strict loading status' do
base_record = UtilSpec::BaseRecord.create!
base_record.strict_loading!
expect(base_record).to be_strict_loading
extended_record = ActiveType::Util.cast(base_record, UtilSpec::ExtendedRecord)
expect(extended_record).to be_strict_loading
end
end

if ActiveRecord::VERSION::MAJOR >= 7
it 'preserves the strict loading mode' do
base_record = UtilSpec::BaseRecord.create!
base_record.strict_loading!(mode: :n_plus_one_only)
expect(base_record.strict_loading_mode).to eq :n_plus_one_only
extended_record = ActiveType::Util.cast(base_record, UtilSpec::ExtendedRecord)
expect(extended_record.strict_loading_mode).to eq :n_plus_one_only
end
end

context 'altering the record used as base for casting' do
it 'to prevent changing it' do
base_record = UtilSpec::BaseRecord.create!(:persisted_string => 'old value')
Expand Down

0 comments on commit 36bd515

Please sign in to comment.