Module: HCast::Caster
- Extended by:
- Concern
- Defined in:
- lib/hcast/caster.rb
Overview
Include this module to create your caster
Example caster:
class ContactCaster
include HCast::Caster
attributes do
hash :contact do
string :name
integer :age, optional: true
float :weight
date :birthday
datetime :last_logged_in
time :last_visited_at
hash :company do
string :name
end
array :emails, each: :string
array :social_accounts, each: :hash do
string :name
symbol :type
end
end
end
end
The defined caster will have #cast method which accepts hash Use it to cast hash:
ContactCaster.new.cast({
contact: {
name: "John Smith",
age: "22",
weight: "65.5",
birthday: "2014-02-02",
last_logged_in: "2014-02-02 10:10:00",
last_visited_at: "2014-02-02 10:10:00",
company: {
name: "MyCo",
},
emails: [ "[email protected]", "[email protected]" ],
social_accounts: [
{
name: "john_smith",
type: 'twitter',
},
{
name: "John",
type: :facebook,
},
]
}
})
The output will be casted hash:
{
contact: {
name: "John Smith",
age: 22,
weight: 65.5,
birthday: Date.parse("2014-02-02"),
last_logged_in: DateTime.parse("2014-02-02 10:10:00"),
last_visited_at: Time.parse("2014-02-02 10:10:00"),
company: {
name: "MyCo",
},
emails: [ "[email protected]", "[email protected]" ],
social_accounts: [
{
name: "john_smith",
type: :twitter,
},
{
name: "John",
type: :facebook,
},
]
}
}
Defined Under Namespace
Modules: ClassMethods