Class: ActionKitApi::ApiDataModel

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

Direct Known Subclasses

Action, Page, User

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ ApiDataModel

Returns a new instance of ApiDataModel.



9
10
11
12
13
# File 'lib/action_kit_api/data_model.rb', line 9

def initialize(hash = {})
  @required_attrs = []

  self.update(hash)
end

Instance Method Details

#saveObject



15
16
17
18
19
20
21
22
23
24
# File 'lib/action_kit_api/data_model.rb', line 15

def save
  class_name = self.class.to_s.split("::").last

  raise MissingRequiredAttributeException "Unable to save incomplete object" unless self.valid?

  response = ActionKitApi::Connection.call("#{class_name}.save_or_create", self.to_hash)

  # Update ourselves to include the data that the server populated 
  self.update(response)
end

#to_hashObject



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/action_kit_api/data_model.rb', line 51

def to_hash
  user_hash = {}

  self.instance_variables.each do |iv|
    key = iv.delete("@").to_sym
    next if key == :required_attrs
    user_hash[key] = self.instance_variable_get(iv)
  end

  user_hash
end

#update(hash = {}) ⇒ Object

Updates all the instance variables in our local object with the values in the hash. This will selectively update only the keys in the hash that is passed, and will not update/add non-existant attributes



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/action_kit_api/data_model.rb', line 30

def update(hash = {})
  hash.each do |k,v|
    # The name of the setter for the value of k
    setter = "#{k}="

    # Check if there is a matching setter
    if self.respond_to?(setter)
      # Yes, there is. Call the setter with the value
      self.send(setter, v)
    end
  end
end

#valid?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
# File 'lib/action_kit_api/data_model.rb', line 43

def valid?
  @required_attrs.each do |k|
    return false if self.send(k).nil?
  end

  true
end