module
URI::Params::Serializable
Overview
TheURI::Params::Serializable module automatically generates methods forx-www-form-urlencoded serializationwhen included.
NOTE To use this module, you must explicitly import itwithrequire "uri/params/serializable".
Example
require "uri/params/serializable"
struct Applicant
include URI::Params::Serializable
getter first_name : String
getter last_name : String
getter qualities : Array(String)
end
applicant = Applicant.from_www_form "first_name=John&last_name=Doe&qualities=kind&qualities=smart"
applicant.first_name # => "John"
applicant.last_name # => "Doe"
applicant.qualities # => ["kind", "smart"]
applicant.to_www_form # => "first_name=John&last_name=Doe&qualities=kind&qualities=smart"
Usage
IncludingURI::Params::Serializablewill create#to_www_form andself.from_www_form methods on the current class.
By default, these methods serialize into awww form encoded string containing the value of every instance variable, the keys being the instance variable name.
Union types are also supported, including unionswith nil.
If multiple types in a union parse correctly, it is undefinedwhich onewill be chosen.
To change how individual instance variables are parsed, the annotationURI::Params::Field can be placed on the instance variable.
Annotating property, getter and setter macros is also allowed.
URI::Params::Field properties:
- ignore: if
trueskip this field in serialization and deserialization (by defaultfalse) - ignore_serialize: if truthy, skip this field in serialization (default:
false). The value can be any Crystal expression and is evaluated at runtime. - ignore_deserialize: if
trueskip this field in deserialization (by defaultfalse) - converter: specify an alternate type for parsing. The converter must define
.from_www_form(params : URI::Params, name : String). An example use casewould be customizing the formatwhen parsingTimeinstances, or supporting a type not natively supported.
Deserialization also respects default values of variables:
require "uri/params/serializable"
struct A
include URI::Params::Serializable
@a : Int32
@b : Float64 = 1.0
end
A.from_www_form("a=1") # => A(@a=1, @b=1.0)
NOTE URI::Params::Serializable defines an internal constructor on any
including type,which means the default constructor (def initialize; end)
is absent unless explicitly defined by the user, evenwhen all instance
variables have a default initializer.