annotation Athena::Serializer::Annotations::Accessor

Overview

Allows using methods/modules to control how a property is retrieved/set.

Fields

Example

Getter/Setter

class AccessorExample
  include ASR::Serializable

  def initialize; end

  @[ASRA::Accessor(getter: get_foo, setter: set_foo)]
  property foo : String = "foo"

  private def set_foo(foo : String) : String
    @foo = foo.upcase
  end

  private def get_foo : String
    @foo.upcase
  end
end

ASR.serializer.serialize AccessorExample.new, :json                 # => {"foo":"FOO"}
ASR.serializer.deserialize AccessorExample, %({"foo":"bar"}), :json # => #<AccessorExample:0x7f5915e25c20 @foo="BAR">

Converter

module ReverseConverter
  def self.deserialize(navigator : ASR::Navigators::DeserializationNavigatorInterface, metadata : ASR::PropertyMetadataBase, data : ASR::Any) : String
    data.as_s.reverse
  end
end

class ConverterExample
  include ASR::Serializable

  @[ASRA::Accessor(converter: ReverseConverter)]
  getter str : String
end

ASR.serializer.deserialize ConverterExample, %({"str":"jim"}), :json # => #<ConverterExample:0x7f9745fa6d60 @str="mij">

Path

class Example
  include ASR::Serializable

  getter id : Int64

  @[ASRA::Accessor(path: {"stats", "HP"})]
  getter hp : Int32

  @[ASRA::Accessor(path: {"stats", "Attack"})]
  getter attack : Int32

  @[ASRA::Accessor(path: {"downs", -1, "last_down"})]
  getter last_down : Time
end

DATA = <<-JSON
{
  "id": 1,
  "stats": {
    "HP": 45,
    "Attack": 49
  },
  "downs": [
    {
      "id": 1,
      "last_down": "2020-05-019T05:23:17Z"
    },
    {
      "id": 2,
      "last_down": "2020-04-07T12:34:56Z"
    }
  ]

}
JSON

ASR.serializer.deserialize Example, DATA, :json
# #<Example:0x7f43c4ddf580
#  @attack=49,
#  @hp=45,
#  @id=1,
#  @last_down=2020-04-07 12:34:56.0 UTC>

Defined in:

annotations.cr