attributes
This commit is contained in:
@@ -51,6 +51,7 @@ module HasAuxTable
|
||||
setup_initialize_hook!(aux_config)
|
||||
setup_save_hook!(aux_config)
|
||||
setup_reload_hook!(aux_config)
|
||||
setup_attributes_hook!(aux_config)
|
||||
setup_relation_extensions!(aux_config)
|
||||
setup_attribute_getter_setter_hooks!(aux_config)
|
||||
|
||||
@@ -306,6 +307,17 @@ module HasAuxTable
|
||||
end
|
||||
end
|
||||
|
||||
sig { params(aux_config: AuxTableConfig).void }
|
||||
def setup_attributes_hook!(aux_config)
|
||||
attributes_method = self.instance_method(:attributes)
|
||||
self.define_method(:attributes) do |*args|
|
||||
T.bind(self, ActiveRecord::Base)
|
||||
ret = attributes_method.bind(self).call(*args)
|
||||
ret.merge!(aux_config.aux_attributes(self))
|
||||
ret
|
||||
end
|
||||
end
|
||||
|
||||
sig do
|
||||
params(
|
||||
aux_table_name: Symbol,
|
||||
|
||||
@@ -102,6 +102,14 @@ module HasAuxTable
|
||||
aux_model.assign_attributes(aux_args)
|
||||
end
|
||||
|
||||
sig do
|
||||
params(main_model: ActiveRecord::Base).returns(T::Hash[Symbol, T.untyped])
|
||||
end
|
||||
def aux_attributes(main_model)
|
||||
aux_model = self.ensure_aux_target(main_model)
|
||||
aux_model.attributes.slice(*self.aux_column_names)
|
||||
end
|
||||
|
||||
sig { returns(T::Array[String]) }
|
||||
def aux_column_names
|
||||
@aux_column_names ||=
|
||||
|
||||
@@ -187,6 +187,20 @@ RSpec.describe HasAuxTable do
|
||||
end
|
||||
end
|
||||
|
||||
it "has the right #attributes" do
|
||||
car =
|
||||
Car.create!(name: "Honda Civic", fuel_type: "gasoline", engine_size: 2.0)
|
||||
expect(car.attributes).to match(
|
||||
"type" => "Car",
|
||||
"id" => car.id,
|
||||
"name" => "Honda Civic",
|
||||
"fuel_type" => "gasoline",
|
||||
"engine_size" => be_within(0.001).of(2.0),
|
||||
"created_at" => be_within(0.001).of(car.created_at),
|
||||
"updated_at" => be_within(0.001).of(car.updated_at)
|
||||
)
|
||||
end
|
||||
|
||||
describe "database integration" do
|
||||
it "provides automatic attribute accessors for auxiliary table columns" do
|
||||
vehicle = Car.create!(name: "Honda Civic")
|
||||
|
||||
Reference in New Issue
Block a user