Class: HashKit::Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_kit/helper.rb

Instance Method Summary collapse

Instance Method Details

#from_hash(hash, klass, transforms = []) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/hash_kit/helper.rb', line 30

def from_hash(hash, klass, transforms =  [])
  obj = klass.new
  if hash ==nil || hash == {}
    return obj
  end

  hash.each do |k,v|
    if !obj.respond_to?(k)
      next
    end
    transform = transforms.detect { |t| t.key.to_sym == k.to_sym }
    if transform != nil
      if v.is_a?(Hash)
        child = from_hash(v, transform.klass, transforms)
        obj.instance_variable_set("@#{k}", child)
      elsif v.is_a?(Array)
        items = v.map do |i|
          from_hash(i, transform.klass, transforms)
        end
        obj.instance_variable_set("@#{k}", items)
      end
    else
      obj.instance_variable_set("@#{k}", v)
    end
  end
  return obj
end

#stringify(hash) ⇒ Object

This method is called to convert all the keys of a hash into strings to allow consistent usage of hashes within your Ruby application.



12
13
14
15
16
# File 'lib/hash_kit/helper.rb', line 12

def stringify(hash)
  {}.tap do |h|
    hash.each { |key, value| h[key.to_s] = map_value_string(value) }
  end
end

#symbolize(hash) ⇒ Object

This method is called to convert all the keys of a hash into symbols to allow consistent usage of hashes within your Ruby application.



5
6
7
8
9
# File 'lib/hash_kit/helper.rb', line 5

def symbolize(hash)
  {}.tap do |h|
    hash.each { |key, value| h[key.to_sym] = map_value_symbol(value) }
  end
end

#to_hash(obj) ⇒ Hash

Convert an object to a hash representation of its instance variables.

Returns:

  • (Hash)

    if the object is not nil, otherwise nil is returned.



20
21
22
23
24
25
26
27
28
# File 'lib/hash_kit/helper.rb', line 20

def to_hash(obj)
  return nil unless obj

  hash = {}
  obj.instance_variables.each do |key|
    hash[key[1..-1].to_sym] = deeply_to_hash(obj.instance_variable_get(key))
  end
  hash
end