Class: DonorsChooseApi::ApiBaseModel

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

Direct Known Subclasses

Project

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ ApiBaseModel

all this should be included



23
24
25
# File 'lib/donors_choose/api_base.rb', line 23

def initialize(hash={})
  update_from_json(hash)
end

Class Method Details

.field(key, options = {}, &block) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/donors_choose/api_base.rb', line 14

def self.field(key, options={}, &block)
  attr_accessor key
  define_method("#{key}=", &block) if block_given?

  self.field_keys[key] = options.fetch(:key, key.to_s)
  self.fields << key
end

.field_keysObject

keeps us in order (until 1.9.x)



10
11
12
# File 'lib/donors_choose/api_base.rb', line 10

def self.field_keys
  @field_keys ||= {}
end

.fieldsObject

this is field behavior, it should be in it’s own module/class



5
6
7
# File 'lib/donors_choose/api_base.rb', line 5

def self.fields
  @fields ||= []
end

Instance Method Details

#attributesObject



37
38
39
40
# File 'lib/donors_choose/api_base.rb', line 37

def attributes
  values = self.class.fields.map { |attribute| self.send(attribute) }
  Hash[self.class.fields.zip(values)]
end

#update_from_json(hash = {}) ⇒ Object

currently, mostly overridden



28
29
30
31
32
33
34
35
# File 'lib/donors_choose/api_base.rb', line 28

def update_from_json(hash={})
  unless hash.empty?
    self.class.fields.each do |field|
      key = self.class.field_keys[field]
      self.send("#{field}=".to_sym, hash[key])
    end
  end
end