Commit f01fdeb2 authored by Daniel Heath's avatar Daniel Heath
Browse files

Fixup: Handle attributes from ruby differently from those fetched from the database

1 merge request!71Implement support for automatically mapping structs
Pipeline #1280 failed with stages
Showing with 19 additions and 13 deletions
+19 -13
......@@ -86,7 +86,7 @@ module Torque
field_names = klass.columns.map(&:name)
attributes = Hash[field_names.zip(fields)]
field_names.each { |field| attributes[field] = klass.type_for_attribute(field).deserialize(attributes[field]) }
build_from_attrs(attributes)
build_from_attrs(attributes, from_database: true)
end
def serialize(value)
......@@ -175,12 +175,17 @@ module Torque
return if value.blank?
return if klass.blank?
return value if value.is_a?(klass)
build_from_attrs(value)
build_from_attrs(value, from_database: false)
end
def build_from_attrs(attributes)
attributes = klass.attributes_builder.build_from_database(attributes, {})
klass.allocate.init_with_attributes(attributes)
def build_from_attrs(attributes, from_database:)
klass.define_attribute_methods
if from_database
attributes = klass.attributes_builder.build_from_database(attributes, {})
klass.allocate.init_with_attributes(attributes)
else
klass.new(attributes)
end
end
end
......
......@@ -4,14 +4,6 @@ require "torque/postgresql/adapter"
module Torque
class BaseStruct
# ActiveRecord modules call `superclass.foo`, so we need an extra layer of inheritance
def initialize(attributes = nil)
@attributes = self.class.attributes_builder.build_from_database
self.class.define_attribute_methods
assign_attributes(attributes) if attributes
yield self if block_given?
end
def to_s
# Avoid printing excessive volumes
"#<#{self.class.name}>"
......@@ -56,7 +48,16 @@ module Torque
include ActiveRecord::Serialization
include ActiveRecord::AttributeAssignment
self.pluralize_table_names = false
def initialize(attributes = nil)
@attributes = self.class.attributes_builder.build_from_database
assign_attributes(attributes) if attributes
self.class.define_attribute_methods
yield self if block_given?
end
class << self
# ActiveRecord modules call `superclass.foo`, so we need an extra layer of inheritance
def database_type
::Torque::PostgreSQL::Adapter::OID::Struct.for_type(table_name, klass: self)
end
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment