Class: Psapi::API_Object

Inherits:
Object
  • Object
show all
Extended by:
Internal
Includes:
Internal, PeercastStation
Defined in:
lib/psapi/api_object.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Internal

camel_to_snake

Methods included from PeercastStation

initialize, #method_missing

Constructor Details

#initialize(hash) ⇒ API_Object

Returns a new instance of API_Object.



54
55
56
# File 'lib/psapi/api_object.rb', line 54

def initialize(hash)
   mass_assign(hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Psapi::PeercastStation

Class Method Details

.accessors_for(camels) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/psapi/api_object.rb', line 13

def accessors_for(camels)
  snakes = camels.map(&method(:camel_to_snake))
  snakes.each do |snake|
    self.class_eval {
      attr_accessor snake.to_sym
    }
  end

  self.class_eval {
    define_method(:to_hash) do
      hash = {}
      snakes.each.with_index do |snake, index|
        hash[camels[index]] = instance_variable_get("@#{snake}")
      end
      hash
    end
  }
end

.define_all_with(method_name) ⇒ Object

APIオブジェクトクラスに all クラスメソッドを追加する



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/psapi/api_object.rb', line 33

def define_all_with(method_name)
  object_klass = self
  self.singleton_class.class_eval do
    define_method(:all) do
      __send__(method_name).map do |item|
        object_klass.new(item)
      end
    end

  end
end

.inherited(klass) ⇒ Object



9
10
11
# File 'lib/psapi/api_object.rb', line 9

def inherited(klass)
  klass.singleton_class.__send__(:include, PeercastStation)
end

Instance Method Details

#mass_assign(hash) ⇒ Object



47
48
49
50
51
52
# File 'lib/psapi/api_object.rb', line 47

def mass_assign(hash)
  hash.each do |key,value|
    sym = ('@' + camel_to_snake(key)).to_sym
    instance_variable_set(sym, value)
  end
end