Class: Chameleon::Model

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

Direct Known Subclasses

Company, Deletion, Event, Profile, SearchItem

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Model

Returns a new instance of Model.



5
6
7
8
9
# File 'lib/chameleon/model.rb', line 5

def initialize(attributes={})
  @attributes = {}

  refresh(attributes)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object (private)



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/chameleon/model.rb', line 67

def method_missing(symbol, *args)
  key = symbol.to_s

  if key[-1] == '=' # setter
    self[key[0..-2]] = args.first
  elsif @attributes.key?(key)
    self[key]
  else
    super
  end
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



3
4
5
# File 'lib/chameleon/model.rb', line 3

def attributes
  @attributes
end

#idObject

Returns the value of attribute id.



2
3
4
# File 'lib/chameleon/model.rb', line 2

def id
  @id
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
# File 'lib/chameleon/model.rb', line 11

def [](key)
  @attributes[key.to_s]
end

#[]=(key, value) ⇒ Object



15
16
17
# File 'lib/chameleon/model.rb', line 15

def []=(key, value)
  @attributes[key.to_s] = Chameleon::Support.value_of(value)
end

#clearObject



23
24
25
# File 'lib/chameleon/model.rb', line 23

def clear
  @attributes.clear
end

#createObject



41
42
43
# File 'lib/chameleon/model.rb', line 41

def create
  Chameleon::Request.post(self)
end

#deleteObject



49
50
51
# File 'lib/chameleon/model.rb', line 49

def delete
  Chameleon::Request.delete(self)
end

#fetchObject



45
46
47
# File 'lib/chameleon/model.rb', line 45

def fetch
  Chameleon::Request.get(self)
end

#inspectObject



53
54
55
56
57
58
# File 'lib/chameleon/model.rb', line 53

def inspect
  string = "#<#{self.class.name}"
  string << " id=#{id}" if id
  string << " attributes=#{attributes}"
  string << '>'
end

#model_nameObject



19
20
21
# File 'lib/chameleon/model.rb', line 19

def model_name
  Chameleon::Support.underscore(self.class.name.gsub('Chameleon::', ''))
end

#refresh(attributes) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/chameleon/model.rb', line 27

def refresh(attributes)
  return self unless attributes.respond_to?(:each_pair)

  attributes.each_pair { |key, value| @attributes[key.to_s] = Chameleon::Support.value_of(value) }
  @id = @attributes.delete('id') if @attributes.key?('id')
  self
end

#urlObject



35
36
37
38
39
# File 'lib/chameleon/model.rb', line 35

def url
  base = "/v3/edit/#{Chameleon::Support.pluralize(model_name)}"
  base << "/#{id}" if id
  base
end