Module: Dry::Monads::JSONCoder
- Defined in:
- lib/dry/monads/extensions/json.rb
Overview
Reads and writes monads as JSON via JSON::Coder.
This replaces the old json/add/dry/monads/maybe file, no longer working from json 3.0, which
removed the whole json/add mechanism, so monads can no longer serialize via JSON.dump and
JSON.load globally. A coder does the same job locally, without patching anything.
The wire format remains unchanged, so JSON written by older versions still loads.
Constant Summary collapse
- JSON_CLASS_KEY =
Key used to tag a serialized monad.
"json_class"- AS_JSON =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Called for every object the generator cannot write natively.
The second argument is
truewhen the object is a hash key andfalseeverywhere else. We do not use it, because a monad never appears as a key, but it must be accepted. lambda { |object, *| case object when Maybe {JSON_CLASS_KEY => object.class.name, "value" => object.none? ? nil : object.value!} else object end }
- ON_LOAD =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Called for every value the parser produces, innermost first.
lambda { |value| next value unless value.is_a?(::Hash) && value.key?(JSON_CLASS_KEY) case value[JSON_CLASS_KEY] when Maybe::Some.name then Maybe::Some.new(value["value"]) when Maybe::None.name then Maybe::None.instance else value end }