lib/ledger_sync/domains/serializer.rb in ledger_sync-domains-1.0.0.rc1 vs lib/ledger_sync/domains/serializer.rb in ledger_sync-domains-1.0.0.rc2
- old
+ new
@@ -12,13 +12,14 @@
# address. This is a same approach, but with dynamic class definition
# to avoid defining methods in unrelated classes. We are using
# SimpleDelegator to delegate these methods into OpenStruct passed in.
# Pure hackery.
klass = Class.new(SimpleDelegator) do
- def self.with_lazy_references(struct, resource:, references:) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
+ def self.with_lazy_references(hash, struct_class:, resource:, references:) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
define_method('valid?') { resource.valid? }
define_method('errors') { resource.errors }
+ define_method('to_hash') { hash }
references.each do |args|
define_method(args.hash_attribute) do
if args.references_many?
resource.try(args.resource_attribute).each do |item|
args.type.serializer.new.serialize(resource: item)
@@ -30,28 +31,34 @@
args.type.serializer.new.serialize(resource: item)
end
end
end
- new(struct)
+ new(struct_class.new(hash))
end
def to_param
id.to_s
end
def persisted?
id.present?
end
+
+ def to_json(*args)
+ JSON.generate(to_hash, *args)
+ end
end
name = self.class.to_s.split('::')
- struct_name = name.pop.sub(/.*\KSerializer/, 'Struct')
+ class_name = name.pop.gsub(/[^0-9a-z ]/i, '').gsub(/.*\KSerializer/, '')
+ struct_name = "#{class_name}Struct"
module_name = name.empty? ? Object : Object.const_get(name.join('::'))
module_name.const_set(struct_name, Class.new(OpenStruct))
klass.with_lazy_references(
- module_name.const_get(struct_name).new(hash),
+ hash,
+ struct_class: module_name.const_get(struct_name),
resource: resource, references: references
)
end
def self.references