Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve readonly and strict_loading status on cast #182

Merged
merged 1 commit into from
Dec 14, 2023
Merged
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
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