Quantcast
Channel: Support - dry-rb discussion forum
Viewing all articles
Browse latest Browse all 268

Customizing Hash

$
0
0

Hi! I’m trying to write a dry-types type useable for parsing a localization API that has data of a strange shape. It’s mostly a hash of String to Hash.map(Types::String, Types::String), but there’s one key which has a completely different value. Something like this:

{
    "blog": {
        "next": "Next page",
        "previous": "Previous page"
    },
    "wizard": {
        "continue": "Click here to continue"
    },
    "garbage": 123
}

I’d prefer to model this as a Hash rather than a Struct because I don’t care what pages are present or what strings they support. However, the presence of this garbage key makes things challenging. I don’t care about this one garbage so I’d like to drop it.

I see dry-rb - dry-types v1.2 - Custom Types shows a bunch of information about defining specific kinds of custom types, but nothing about my use case. Is it enough to e.g. subclass Nominal and override call? I did that and it worked, but from looking at the code, I get the impression that the actual calling contract is that I should support calling call_unsafe, call_safe,

For the record, this worked:

    without_garbage = Class.new(Dry::Types::Nominal) do
      def initialize(wrapped)
        @wrapped = wrapped
        super(::Hash)
      end

      def call(input = Undefined, &block)
        if input.is_a?(Hash)
          input.delete("garbage")
        end
        @wrapped.call(input, &block)
      end
    end
    attribute :localized_strings, without_garbage.new(Types::Hash.map(Types::String, Types::Hash.map(Types::String, Types::String)))

4 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 268

Latest Images

Trending Articles





Latest Images