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

Provide a way decorate_attribute for attribute type decoration #41262

Closed
wants to merge 1 commit into from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions activerecord/lib/active_record/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,12 @@ def load_schema! # :nodoc:
end
end

def decorate_attribute(name, type_name, default: NO_DEFAULT_PROVIDED, **options)
attribute(name, default: default) do |subtype|
Type.lookup(type_name, **options, subtype: subtype, adapter: Type.adapter_name_from(self))
end
end

private
NO_DEFAULT_PROVIDED = Object.new # :nodoc:
private_constant :NO_DEFAULT_PROVIDED
Expand Down
18 changes: 18 additions & 0 deletions activerecord/test/cases/serialized_attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,24 @@ def changed_in_place?(old, new)
end
end

def test_decorate_attribute_on_serialized_attribute
old_registry = ActiveRecord::Type.registry
ActiveRecord::Type.registry = ActiveRecord::Type.registry.dup
ActiveRecord::Type.register :encrypted, EncryptedType

klass = Class.new(ActiveRecord::Base) do
self.table_name = Topic.table_name
store :content
decorate_attribute :content, :encrypted
end

topic = klass.create!(content: { trial: true })

assert_equal({ "trial" => true }, topic.content)
ensure
ActiveRecord::Type.registry = old_registry
end

def test_decorated_type_with_type_for_attribute
old_registry = ActiveRecord::Type.registry
ActiveRecord::Type.registry = ActiveRecord::Type.registry.dup
Expand Down