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

Returns a new instance of Base.



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

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(options) ⇒ Object



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

def self.direct_arrays options
  @arrays = []
  options.each do |name,type|
    @arrays << [name,type]
    self.class_eval("def #{name};@#{name};end")
    self.class_eval("def #{name}=(val);@#{name}=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(options) ⇒ Object



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

def self.direct_objects options
  @objects = []
  options.each do |name,type|
    @objects << [name,type]
    self.class_eval("def #{name};@#{name};end")
    self.class_eval("def #{name}=(val);@#{name}=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
55
56
# 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 not value.nil?
    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 |name,_|
    object = send(name)
    next if object.nil?
    value_hash = send(name).to_hash || {}
    next if value_hash.empty?
    result[name] = value_hash
  end
  result
end