Sha256: 49a98f5930b4fb6820058616f1ba7abadf10b5ad17487127228917118f6e7d5a

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

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

  def fields_information
    # We add account and environment, which are common in all resources
    self
      .class
      .fields_information
      .merge(
        account:     :string,
        environment: :string
      )
  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

1 entries across 1 versions & 1 rubygems

Version Path
invofox-api-ruby-0.1.2 lib/invofox/resource.rb