attributes

This commit is contained in:
Dylan Knutson
2025-07-17 22:03:47 +00:00
parent d83d6833ad
commit d112d8b72d
3 changed files with 34 additions and 0 deletions

View File

@@ -51,6 +51,7 @@ module HasAuxTable
setup_initialize_hook!(aux_config) setup_initialize_hook!(aux_config)
setup_save_hook!(aux_config) setup_save_hook!(aux_config)
setup_reload_hook!(aux_config) setup_reload_hook!(aux_config)
setup_attributes_hook!(aux_config)
setup_relation_extensions!(aux_config) setup_relation_extensions!(aux_config)
setup_attribute_getter_setter_hooks!(aux_config) setup_attribute_getter_setter_hooks!(aux_config)
@@ -306,6 +307,17 @@ module HasAuxTable
end end
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 sig do
params( params(
aux_table_name: Symbol, aux_table_name: Symbol,

View File

@@ -102,6 +102,14 @@ module HasAuxTable
aux_model.assign_attributes(aux_args) aux_model.assign_attributes(aux_args)
end 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]) } sig { returns(T::Array[String]) }
def aux_column_names def aux_column_names
@aux_column_names ||= @aux_column_names ||=

View File

@@ -187,6 +187,20 @@ RSpec.describe HasAuxTable do
end end
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 describe "database integration" do
it "provides automatic attribute accessors for auxiliary table columns" do it "provides automatic attribute accessors for auxiliary table columns" do
vehicle = Car.create!(name: "Honda Civic") vehicle = Car.create!(name: "Honda Civic")