Class: HashCast::RecursiveCasterApplicator

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_cast/recursive_caster_applicator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes, options) ⇒ RecursiveCasterApplicator



4
5
6
7
# File 'lib/hash_cast/recursive_caster_applicator.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/hash_cast/recursive_caster_applicator.rb', line 2

def attributes
  @attributes
end

#optionsObject (readonly)

Returns the value of attribute options.



2
3
4
# File 'lib/hash_cast/recursive_caster_applicator.rb', line 2

def options
  @options
end

Instance Method Details

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



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

def cast(input_hash, opts = {})
  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 HashCast::Errors::AttributeError => e
        handle_attribute_error(e, attribute)
      end
    else
      raise HashCast::Errors::MissingAttributeError.new("should be given", attribute.name) if attribute.required?
    end
  end

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

  casted_hash
end