module NubeFact::Utils

Public Instance Methods

as_json(options={}) click to toggle source
Fix to bug due to ActiveSupport::Serialization JSON.
 it calls as_json in order to get the hash representation of the object
 ActiveSupport uses all object attributes, including item.invoice who force
 the json convertion into an infinite loop:

. (invoice -> items -> item -> invoice -> items -> item …)

# File lib/util/utils.rb, line 21
def as_json(options={})
  Hash[to_h.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }]
end
to_h() click to toggle source

This iterates over all fields and if is an array (items and guias) converts it to hash using to_h

# File lib/util/utils.rb, line 4
def to_h
  Hash[self.class::FIELDS.map do |field| 
    value = send(field)
    value = value.map &:to_h if value.is_a? Array
    [field, value]
  end]
end
to_json(options = {}) click to toggle source
# File lib/util/utils.rb, line 12
def to_json(options = {})
  self.to_h.to_json options
end

Private Instance Methods

load_data_from_param(data_hash) click to toggle source
# File lib/util/utils.rb, line 35
def load_data_from_param(data_hash)
  data_hash.each do|key, value|
    if self.class.const_defined?('AUTO_CALCULATED_FIELDS') \
      && self.class::AUTO_CALCULATED_FIELDS.include?(key)
      warn("field #{key} will be calculated automatically, you don't need to pass it.")
    end
    
    begin
      send "#{key}=", value
    rescue NoMethodError => e
      raise NubeFact::InvalidField.new "Invalid Field: #{key}"
    end
  end

  set_default_data
end
set_default_data() click to toggle source
# File lib/util/utils.rb, line 26
def set_default_data
  self.class::DEFAULT_DATA.each do |field, value|
    next if send(field)

    value = value.call(self) if value.kind_of? Proc
    send "#{field}=", value
  end
end