Add read_attribute_for_database

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.
This commit is contained in:
Jonathan Hefner 2022-10-18 15:42:01 -05:00
parent 6676989957
commit fecd8becbe
2 changed files with 29 additions and 2 deletions

@ -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

@ -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 }
@ -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