Class: MxHero::API::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/resource.rb

Overview

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

Direct Known Subclasses

Cos, Domain, Feature

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Resource

Returns a new instance of Resource.



48
49
50
51
52
53
54
55
56
57
# 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

Class Method Details

.attribute(name, more = {}) ⇒ Object

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’



32
33
34
35
36
37
# 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) ⇒ Object

Create a list of attributes

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



44
45
46
# File 'lib/resource.rb', line 44

def self.attributes(*attrs)
  attrs.each { |attr| attribute(attr) }
end

Instance Method Details

#to_jsonObject



59
60
61
62
63
64
65
66
67
68
69
70
# 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