Module: Mixins

Instance Method Summary collapse

Instance Method Details

#cadooz_class(klass) ⇒ Object



36
37
38
39
40
# File 'lib/mixins.rb', line 36

def cadooz_class(klass)
  klass = klass.name.split('::').last.to_sym

  Cadooz.constants.include?(klass)
end

#default_value_for_nilObject



42
43
44
45
46
47
# File 'lib/mixins.rb', line 42

def default_value_for_nil
  self.instance_variables.each do |var|
    value = self.instance_variable_get(var)
    self.instance_variable_set(var, 'not available') if value.blank?
  end
end

#instance_variables_empty?(instance) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
# File 'lib/mixins.rb', line 28

def instance_variables_empty?(instance)
  instance.instance_variables.each do |var|
    return false unless instance.instance_variable_get(var).blank?
  end

  true
end

#serialize(data_only = false) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/mixins.rb', line 2

def serialize(data_only = false)
  class_name = self.class.to_s.gsub(/Cadooz::[a-z]*::/i, '').underscore
  result = data_only ? {} : { class_name.to_sym => {} }

  hash_assign = ->name, value { data_only ? result[name] = value : result[class_name.to_sym][name] = value }

  self.instance_variables.each do |var|
    name = var.to_s.gsub('@', '').to_sym
    value = self.instance_variable_get(var)

    if value.class.method_defined? :serialize
      hash_assign.(name, value.serialize(true)) unless instance_variables_empty?(value)
    elsif value.class == Array
      arr = []
      value.each do |val|
        arr << val.serialize(true) unless instance_variables_empty?(val)
      end
      hash_assign.(name, arr) unless arr.blank?
    elsif !cadooz_class(value.class)
      hash_assign.(name, value) unless value.blank?
    end
  end

  result
end