class Crinder::Base(T)
- Crinder::Base(T)
- Reference
- Object
Overview
Crinder::Base
is the base renderer of type T
.
To define your own renderer, you need to inherit Crinder::Base
with specific type and declare the fields with field
.
For example, this is a renderer of Time
.
class TimeRenderer < Crinder::Base(Time)
field year : Int
field month : Int
field day : Int
field hour : Int
field minute : Int
field second : Int
end
Then .render
will be auto generated.
time = Time.new(2018, 3, 15, 16, 21, 1)
TimeRenderer.render(time) # => "{\"year\":2018,\"month\":3,\"day\":15,\"hour\":16,\"minute\":21,\"second\":1}"
Defined in:
crinder.crConstant Summary
-
SETTINGS =
{} of Nil => Nil
Class Method Summary
-
.object
the getter of the object to be rendered, which can be called in
value
,if
orunless
Macro Summary
-
field(decl, **options)
Defines a field.
-
remove(name)
Undefines a field.
Class Method Detail
def self.object
#
the getter of the object to be rendered, which can be called in value
, if
or unless
Macro Detail
macro field(decl, **options)
#
Defines a field.
Example
Usage
field
requries a name or a type declaration and a series of named arguments as options.
field name : type, **options
- name: (required) the field name to be rendered
- type: the type for auto casting. For example, if it is
String
,#to_s
of the field will be called for rendering. This is JSON Type but not Crystal Type, so it must be one of JSON::Type, and should beInt
instead ofInt64
orInt32
if this field is integer. If it isNil
or not provided, no casting method will be performed. - value: a lambda, a class method or a constant to replace the value. By default, it is an auto generated class method
name
which casting the field totype
. Ifvalue
is provided,type
becomes useless becausevalue
replaces the auto generated class method. However, it is still recommended to declare the type for understandability. - with: a renderer for this field. This field will be filtered by
type
andvalue
before passing to it. It is not necessary to be a subclass ofCrinder::Base
, but it must have the class methodrender(object : T, json : JSON::Builder)
whereT
is the original type of this field. - if: a lambda, a class method or a constant to determine whether to show this field.
- unless: opposite of
if
. If bothif
andunless
are provided, this field is only showed whenif
is truthy andunless
is falsey.