Class: Yandex::API::Direct::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/yandex-api/direct/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Base



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/yandex-api/direct/base.rb', line 55

def initialize(params = {})
  params.each do |key, value|
    object = self.class.objects.find{|s| s.first.to_sym == key.to_sym}
    array = self.class.arrays.find{|s| s.first.to_sym == key.to_sym}
    if object
      send("#{key}=", object.last.new(value))
    elsif array
      send("#{key}=", value.collect {|element| array.last.new(element)})
    else
      send("#{key}=", value) if respond_to? "#{key}="
    end
  end
end

Class Method Details

.arraysObject



21
# File 'lib/yandex-api/direct/base.rb', line 21

def self.arrays ; @arrays || [] ; end

.attributesObject



3
# File 'lib/yandex-api/direct/base.rb', line 3

def self.attributes ; @attributes || [] ; end

.direct_arrays(*args) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/yandex-api/direct/base.rb', line 22

def self.direct_arrays *args
  @arrays = []
  args.each do |array,type|
    @arrays << [array,type]
    self.class_eval("def #{array};@#{array};end")
    self.class_eval("def #{array}=(val);@#{array}=val;end")          
  end
end

.direct_attributes(*args) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/yandex-api/direct/base.rb', line 4

def self.direct_attributes *args
  @attributes = []
  args.each do |arg|
    @attributes << arg
    self.class_eval("def #{arg};@#{arg};end")
    self.class_eval("def #{arg}=(val);@#{arg}=val;end")          
  end
end

.direct_objects(*args) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/yandex-api/direct/base.rb', line 13

def self.direct_objects *args
  @objects = []
  args.each do |object,type|
    @objects << [object,type]
    self.class_eval("def #{object};@#{object};end")
    self.class_eval("def #{object}=(val);@#{object}=val;end")          
  end
end

.objectsObject



12
# File 'lib/yandex-api/direct/base.rb', line 12

def self.objects ; @objects || [] ; end

Instance Method Details

#to_hashObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/yandex-api/direct/base.rb', line 30

def to_hash
  result = {}
  # build hash of attributes
  self.class.attributes.each do |attribute|
    value = send(attribute)
    next unless value.present?
    result[attribute] = value
  end
  # build hash of arrays
  self.class.arrays.each do |array,type|
    data_array = send(array)|| []
    next if data_array.empty?
    result[array] = []
    data_array.each do |data|
      result[array] << data.to_hash
    end
  end
  # build hash of objects
  self.class.objects.each do |object,type|
    value_hash = send(object).try(:to_hash) || {}
    next if value_hash.empty?
    result[object] = value_hash
  end
  result
end