Module: Storazzo::Hashify

Included in:
RicDisk
Defined in:
lib/storazzo/hashify.rb

Instance Method Summary collapse

Instance Method Details

#ivars_excluded_from_hashObject

Classes that include this module can exclude certain instance variable from its hash representation by overriding this method



9
10
11
# File 'lib/storazzo/hashify.rb', line 9

def ivars_excluded_from_hash
  ['this_doesnt_exist']
end

#obj_to_hashObject



31
32
33
34
35
36
37
38
39
# File 'lib/storazzo/hashify.rb', line 31

def obj_to_hash
  h = {}
  puts self
  instance_variables.each do |var|
    # puts var
    h[var.to_s.delete('@')] = instance_variable_get(var) # send(var.to_s.delete('@'))
  end
  h
end

#obj_to_yamlObject



45
46
47
# File 'lib/storazzo/hashify.rb', line 45

def obj_to_yaml
  obj_to_hash.to_yaml
end

#to_hashObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/storazzo/hashify.rb', line 13

def to_hash
  hash = {}
  excluded_ivars = ivars_excluded_from_hash

  # Iterate over all the instance variables and store their
  # names and values in a hash
  instance_variables.each do |var|
    next if excluded_ivars.include? var.to_s

    value = instance_variable_get(var)
    value = value.map(&:to_hash) if value.is_a? Array

    hash[var.to_s.delete('@')] = value
  end

  hash
end

#to_yamlObject



41
42
43
# File 'lib/storazzo/hashify.rb', line 41

def to_yaml
  to_hash.to_yaml
end