Simple version of `StrongJSON::Type::Object#update_fields`
Opened this issue · 0 comments
ybiquitous commented
Hello,
I want a method such as StrongJSON::Type::Object#merge
, but is this idea reasonable and has a value to consider?
class StrongJSON
module Type
class Object
def merge(other_object_type, *other_object_types)
new_fields = fields.merge(*[other_object_type, *other_object_types].map(&:fields))
self.class.new(new_fields, on_unknown: on_unknown, exceptions: exceptions)
end
end
end
end
# Usage
Base = StrongJSON.new do
let :config, object(root: string)
end
Foo = StrongJSON.new do
let :config, object(disabled: boolean?)
end
Bar = StrongJSON.new do
let :config, object(enabled: boolean?)
end
Baz = StrongJSON.new do
let :config, Base.config.merge(Foo.config, Bar.config)
end
Baz.config.coerce({ root: "/" })
#=> {:root=>"/", :disabled=>nil, :enabled=>nil}
When using StrongJSON::Type::Object#update_fields
, the code becomes a bit long:
Baz2 = StrongJSON.new do
let :config, Base.config.update_fields { |fields|
fields.merge!(Foo.config.fields, Bar.config.fields)
}
end
Baz2.config.coerce({ root: "/" })
#=> {:root=>"/", :disabled=>nil, :enabled=>nil}