Skip to content

Commit

Permalink
Add read_attribute_for_database
Browse files Browse the repository at this point in the history
The `BeforeTypeCast` module defines `read_attribute_before_type_cast`,
`attributes_before_type_cast`, and `*_before_type_cast` attribute
methods.  It also defines `attributes_for_database` and `*_for_database`
attribute methods, but no corresponding `read_attribute_for_database`
method.

This commit adds the missing `read_attribute_for_database` method.
  • Loading branch information
jonathanhefner committed Oct 20, 2022
1 parent 6676989 commit fecd8be
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
Expand Up @@ -52,6 +52,23 @@ def read_attribute_before_type_cast(attr_name)
attribute_before_type_cast(name)
end

# Returns the value of the attribute identified by +attr_name+ after
# serialization.
#
# class Book < ActiveRecord::Base
# enum status: { draft: 1, published: 2 }
# end
#
# book = Book.new(status: "published")
# book.read_attribute(:status) # => "published"
# book.read_attribute_for_database(:status) # => 2
def read_attribute_for_database(attr_name)
name = attr_name.to_s
name = self.class.attribute_aliases[name] || name

attribute_for_database(name)
end

# Returns a hash of attributes before typecasting and deserialization.
#
# class Task < ActiveRecord::Base
Expand Down
14 changes: 12 additions & 2 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -215,7 +215,17 @@ def setup
end
end

test "read attributes_for_database" do
test "read_attribute_for_database" do
topic = Topic.new(content: ["ok"])
assert_equal "---\n- ok\n", topic.read_attribute_for_database("content")
end

test "read_attribute_for_database with aliased attribute" do
topic = Topic.new(title: "Hello")
assert_equal "Hello", topic.read_attribute_for_database(:heading)
end

test "attributes_for_database" do
topic = Topic.new
topic.content = { "one" => 1, "two" => 2 }

Expand All @@ -226,7 +236,7 @@ def setup
assert_not_equal topic.attributes, before_type_cast_attributes
end

test "read attributes_after_type_cast on a date" do
test "read attributes after type cast on a date" do
tz = "Pacific Time (US & Canada)"

in_time_zone tz do
Expand Down

0 comments on commit fecd8be

Please sign in to comment.