Next-gen ruby libs! » github.com/dry-rb » website: https://dry-rb.org » forum: https://discourse.dry-rb.org
defines
method of the dry-core
gem, but i’m not sure if its actually a bug.require "dry/struct"
require "dry/core/class_attributes"
class Type < Dry::Struct
extend Dry::Core::ClassAttributes
defines :mappings
mappings({})
transform_keys { |key| reverse_mapping_for(key.to_sym) }
class << self
def reverse_mapping_for(attribute)
mappings.key(attribute) || attribute
end
end
end
class Resource < Type
defines :resource_name
end
class Relation < Resource
resource_name "relaties"
mappings(type: :relatiesoort, name: :naam)
attribute :id, Types::Strict::String
attribute :type, Types::Array(Types::Strict::String)
attribute :name, Types::Strict::String
attribute :email, Types::Strict::String
end
# NOTE: note the difference between “naam" and “name"
Relation.new(id: "1", type: ["Klant"], naam: "Rick", email: "rick@example.com")
# mappings returns an empty hash when called inside the `reverse_mapping_for` method
# Dry::Struct::Error: [Relation.new] :name is missing in Hash input
# If i move the `transform_keys` method call to the Relation class it works:
class Relation < Resource
transform_keys { |key| reverse_mapping_for(key.to_sym) }
resource_name "relaties"
mappings(type: :relatiesoort, name: :naam)
attribute :id, Types::Strict::String
attribute :type, Types::Array(Types::Strict::String)
attribute :name, Types::Strict::String
attribute :email, Types::Strict::String
end
# NOTE: note the difference between “naam" and “name"
Relation.new(id: "das", type: ["Klant"], naam: "test", email: "asdsa")
=> #<Relation id="das" type=["Klant"] name="test" email="asdsa" establishment_address=nil>
transform_keys
is bound to Type
, that's why reverse_mapping_for
is always called on this object
inherited
to work around this, you'll need to call transform_keys
in every subclass so that the context is not bound to Type
def inherited(subclass)
puts subclass
subclass.transform_keys { |key| reverse_mapping_for(key.to_sym) }
super
end
Something like this? Bc now a get a different error: “dry/struct/class_interface.rb:186:in transform_keys': undefined method
with_key_transform' for nil:NilClass”
subclass.reverse_mapping_for
rule(some_rule: [:type]) do |type|
type.included_in?(VALID_TYPES).then(
required(:other_field).schema(SomeFeature.enabled? ? SchemaOne : SchemaTwo)
)
end