class Crinder::Base(T)

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.cr

Constant Summary

SETTINGS = {} of Nil => Nil

Class Method Summary

Macro Summary

Class Method Detail

def self.object #

the getter of the object to be rendered, which can be used in value, if or unless


[View source]

Macro Detail

macro field(decl, **options) #

Defines a field.

Example

See README or Overview.

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
  • as: the name to be replaced in the rendered json
  • 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 it should be Int instead of Int64 or Int32 if this field is integer, and so does Float. If it is Nil 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 to type. If value is provided, type becomes useless because value replaces the auto generated class method. However, it is still recommended to declare type for understandability. Don't use value and as together because it makes name meaningless.
  • with: a renderer for this field. This field will be filtered by value before passing to it. It is not necessary to be a subclass of Crinder::Base, but it must have the class method render(object : T, json : JSON::Builder) where T 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 both if and unless are provided, this field is only showed when if is truthy and unless is falsey.

[View source]
macro remove(name) #

Undefines a field.


[View source]