Class: HCast::AttributesCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/hcast/attributes_caster.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes, options) ⇒ AttributesCaster

Returns a new instance of AttributesCaster.



4
5
6
7
# File 'lib/hcast/attributes_caster.rb', line 4

def initialize(attributes, options)
  @attributes         = attributes
  @options            = options
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



2
3
4
# File 'lib/hcast/attributes_caster.rb', line 2

def attributes
  @attributes
end

#optionsObject (readonly)

Returns the value of attribute options.



2
3
4
# File 'lib/hcast/attributes_caster.rb', line 2

def options
  @options
end

Instance Method Details

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/hcast/attributes_caster.rb', line 9

def cast(input_hash, options = {})
  casted_hash = {}

  hash_keys = get_keys(input_hash)
  attributes.each do |attribute|
    if hash_keys.include?(attribute.name)
      begin
        casted_value = cast_attribute(attribute, input_hash)
        casted_hash[attribute.name] = casted_value
      rescue HCast::Errors::AttributeError => e
        e.add_namespace(attribute.name)
        raise e
      end
    else
      raise HCast::Errors::MissingAttributeError.new("should be given", attribute.name)if attribute.required?
    end
  end

  if !options[:skip_unexpected_attributes]
    check_unexpected_attributes_not_given!(hash_keys, casted_hash.keys)
  end

  casted_hash
end