module Enum::ValueConverter(T)

Overview

Converter for value-based serialization and deserialization of enum type T.

The serialization format of Enum#to_nason and Enum.from_nason is based on the member name. This converter offers an alternative based on the member value.

This converter can be used for its standalone serialization methods as a replacement of the default strategy of Enum. It also works as a serialization converter with NASON::Field and YAML::Field

require "nason"
require "yaml"

enum MyEnum
  ONE = 1
  TWO = 2
end

class Foo
  include NASON::Serializable
  include YAML::Serializable

  @[NASON::Field(converter: Enum::ValueConverter(MyEnum))]
  @[YAML::Field(converter: Enum::ValueConverter(MyEnum))]
  property foo : MyEnum = MyEnum::ONE

  def initialize(@foo)
  end
end

foo = Foo.new(MyEnum::ONE)
foo.to_nason # => %({"foo":1})
foo.to_yaml  # => %(---\nfoo: 1\n)

NOTE Automatically assigned enum values are subject to change when the order of members by adding, removing or reordering them. This can affect the integrity of serialized data between two instances of a program based on different code versions. A way to avoid this is to explicitly assign fixed values to enum members.

Defined in:

nason/from_json.cr
nason/to_json.cr

Constructors

Class Method Summary

Constructor Detail

def self.new(pull : NASON::PullParser) : T #

[View source]

Class Method Detail

def self.from_nason(pull : NASON::PullParser) : T #

Reads a serialized enum member by value from pull.

See .to_nason for reference.

Raises NASON::ParseException if the deserialization fails.


[View source]
def self.to_nason(value : T, io : IO) #

[View source]
def self.to_nason(member : T, json : NASON::Builder) #

Serializes enum member member by value.

For both flags enums and non-flags enums, the value of the enum member is used for serialization.

enum Stages
  INITIAL
  SECOND_STAGE
end

Enum::ValueConverter.to_nason(Stages::INITIAL)      # => %(0)
Enum::ValueConverter.to_nason(Stages::SECOND_STAGE) # => %(1)

@[Flags]
enum Sides
  LEFT
  RIGHT
end

Enum::ValueConverter.to_nason(Sides::LEFT)                # => %(1)
Enum::ValueConverter.to_nason(Sides::LEFT | Sides::RIGHT) # => %(3)
Enum::ValueConverter.to_nason(Sides::All)                 # => %(3)
Enum::ValueConverter.to_nason(Sides::None)                # => %(0)

Enum#to_nason offers a different serialization strategy based on the member name.


[View source]
def self.to_nason(value : T) #

[View source]