class MxHero::API::Resource

Base resource

Example of use:

class User < MxHero::API::Resource
  attribute :first_name, map: 'firstName'  # Map the resource attribute (hash key) from firstName
  attribute :last_name,  map: 'lastName'
  attribute :updated, date: true
  attribute :age
end

The map in attribute indicate that can build an instance with a Hash that contains :firstName to set first_name instance attribute.

Or:

class User < MxHero::API::Resource
  attributes :first_name, :last_name, :age
end

Public Class Methods

attribute(name, more = {}) click to toggle source

Create an instance attribute and accessors If indicate map in more parameter (ex.: map: 'firstName') that can be set in the construction with a Hash that contains :firstName Can use date: true to manage date fields as Unix epoch integers

Ex.: attribute :first_name, map: 'firstName'

# File lib/resource.rb, line 32
def self.attribute(name, more = {})
  instance_variable_set(:"@#{name}", nil)
  attr_accessor :"#{name}"
  map(name, more[:map]) if more.has_key?(:map)
  date_accessor(name) if more.fetch(:date, false)
end
attributes(*attrs) click to toggle source

Create a list of attributes

Ex.: attributes :first_name, :last_name, :age

# File lib/resource.rb, line 44
def self.attributes(*attrs)
  attrs.each { |attr| attribute(attr) }
end
new(data) click to toggle source
# File lib/resource.rb, line 48
def initialize(data)
  return unless data
  data.each do |variable, value|
    set = "#{variable}="
    send(set, value) if respond_to? set
  end
  self.class.mappings.each do |attr, map|
    send("#{attr}=", data[map]) if data.key?(map) 
  end
end

Private Class Methods

date_accessor(attribute) click to toggle source
# File lib/resource.rb, line 87
def self.date_accessor(attribute)
  @date_attributes ||= []
  @date_attributes << attribute
 
  # Redefine the setter to support Unix Epoch (integer or string) or date
  define_method("#{attribute}=") do |date| 
    if date.is_a? Integer or date.is_a? String
      instance_variable_set "@#{attribute}", DateTime.strptime(date.to_s, '%Q')
    else
      instance_variable_set "@#{attribute}", date
    end
  end

end
date_attributes() click to toggle source
# File lib/resource.rb, line 83
def self.date_attributes
  @date_attributes || []
end
map(attr, map) click to toggle source
# File lib/resource.rb, line 78
def self.map(attr, map)
  @mappings ||= {}
  @mappings[attr.to_sym] = map.to_sym
end
mappings() click to toggle source
# File lib/resource.rb, line 74
def self.mappings
  @mappings
end

Public Instance Methods

to_json() click to toggle source
# File lib/resource.rb, line 59
def to_json
  hash = Hash.new
  instance_variables.each do |variable|
    attr = variable[1..-1].to_sym
    key = self.class.mappings.fetch(attr, attr)
    hash[key] = instance_variable_get(variable)
    if self.class.date_attributes.include?(attr)
      hash[key] = hash[key].strftime('%Q')
    end
  end
  hash.to_json
end