Sha256: 9caccc772b2f64b9125c65331ae720070ca58bf64280defe5cdf7aa4235eefe1

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 KB

Contents

class Invofox::Resource
  def initialize(data)
    generate_attr_readers
    set_data(data)
  end

  def fields_information
    self.class.fields_information
  end

  private

  def generate_attr_readers
    fields_information.each do |field, _|
      define_singleton_method(field) do
        instance_variable_get("@#{field}")
      end
    end
  end

  def set_data(data)
    fields_information.each do |field, type|
      next unless data.key?(field.to_s) || data[field.to_sym]

      raw_value = data[field.to_s] || data[field.to_sym]
      value = value_for(raw_value, type)
      instance_variable_set("@#{field}", value)
    end
  end

  def value_for(raw_value, type)
    case type
    when :boolean
      [true, "1", 1].include?(raw_value)
    when :time
      if raw_value.is_a?(Time)
        raw_value
      else
        Time.parse(raw_value)
      end
    else
      raw_value
    end
  end

  class << self
    def fields_information
      @fields_information
    end

    def has_fields(fields_information)
      @fields_information = fields_information.merge("_id" => :string)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
invofox-api-ruby-0.1.1 lib/invofox/resource.rb
invofox-api-ruby-0.1.0 lib/invofox/resource.rb