Module: HashCast::Caster::ClassMethods

Defined in:
lib/hashcast/caster.rb

Constant Summary collapse

ALLOWED_OPTIONS =
[:string, :symbol]

Instance Method Summary collapse

Instance Method Details

#attributes(&block) ⇒ Object

Defines casting rules

Examples:

attributes do
  string   :first_name
  string   :last_name
  integer  :age, optional: true
end

Raises:

  • (ArgumentError)


92
93
94
95
96
97
# File 'lib/hashcast/caster.rb', line 92

def attributes(&block)
  raise ArgumentError, "You should provide block" unless block_given?

  attributes = HashCast::AttributesParser.parse(&block)
  self.instance_variable_set(:@attributes, attributes)
end

#cast(hash, options = {}) ⇒ Object

Performs casting

Parameters:

  • hash (Hash)

    hash for casting

  • options (Hash) (defaults to: {})

    options, input_keys: :string, output_key: :symbol



102
103
104
105
106
107
108
109
110
# File 'lib/hashcast/caster.rb', line 102

def cast(hash, options = {})
  check_attributes_defined!
  check_hash_given!(hash)
  check_options!(options)
  options = set_default_options(options)

  attributes_caster = HashCast::AttributesCaster.new(instance_variable_get(:@attributes), options)
  attributes_caster.cast(hash)
end