Class: ActionKitApi::ApiDataModel

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

Direct Known Subclasses

Action, Event, EventCampaign, Page, User

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ ApiDataModel

Returns a new instance of ApiDataModel.



11
12
13
14
15
16
17
18
# File 'lib/action_kit_api/data_model.rb', line 11

def initialize(hash = {})
  @required_attrs ||= []
  @read_only_attrs ||= []
  @read_only_attrs << :created_at
  @read_only_attrs << :updated_at

  self.update(hash)
end

Instance Attribute Details

#created_atObject

All the different types of objects have at least these



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

def created_at
  @created_at
end

#updated_atObject

All the different types of objects have at least these



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

def updated_at
  @updated_at
end

Instance Method Details

#saveObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/action_kit_api/data_model.rb', line 20

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

  raise MissingRequiredAttributeException unless self.valid?

  attrs_hash = self.to_hash
  attrs_hash.delete_if do |k, v| 
    @read_only_attrs.include?(k)
  end

  response = ActionKitApi.connection.call("#{class_name}.save_or_create", attrs_hash)

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

#to_hashObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/action_kit_api/data_model.rb', line 61

def to_hash
  user_hash = {}

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

  # XMLRPC::Client doesn't like empty values
  user_hash.delete_if do |k, v|
    v.to_s.empty? || v.nil?
  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



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/action_kit_api/data_model.rb', line 40

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)


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

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

  true
end