Module: Hook::Model::InstanceMethods

Included in:
Hook::Model
Defined in:
lib/hook-client/model.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object

Delegator methods



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/hook-client/model.rb', line 65

def method_missing(m, *args, &block)
  res = @collection.send(m, *args, &block)

  # Check for success/error responses
  if res.kind_of?(Hash) && res.length == 1
    return res['success'] unless res['success'].nil?
    throw RuntimeError.new(res['error']) unless res['error'].nil?
  end

  if (res.kind_of?(Hook::Collection))
    self
  else
    (res.kind_of?(Array)) ? res.map {|r| self.class.new(r) } : self.class.new(res)
  end
end

Instance Method Details

#attributesObject



56
57
58
# File 'lib/hook-client/model.rb', line 56

def attributes
  @attributes
end

#attributes=(attrs) ⇒ Object



52
53
54
# File 'lib/hook-client/model.rb', line 52

def attributes=(attrs)
  @attributes = attrs
end

#initialize(attrs = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hook-client/model.rb', line 26

def initialize(attrs = {})
  # is Hook::Client configured?
  throw RuntimeError.new("Please use Hook::Client.configure.") unless Hook::Client.instance

  @collection = Hook::Client.instance.collection(self.class.collection_name)
  self.attributes = {}
  attrs.each_pair do |name, value|
    self.send(:"#{name}=", value) if self.respond_to?(:"#{name}")
  end

  # reset_changes
  changes_applied if self._id
end

#inspectObject



60
61
62
# File 'lib/hook-client/model.rb', line 60

def inspect
  "#<#{self.class.name}: attributes=#{attributes.inspect}>"
end

#saveObject



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hook-client/model.rb', line 40

def save
  return false if !self.changed? || !self.valid?

  changes_applied
  if self._id.nil?
    self.attributes = @collection.update(self._id, attributes)
  else
    self.attributes = @collection.create(attributes)
  end
  self
end