Class: Pandoru::Models::Base
- Inherits:
-
Object
- Object
- Pandoru::Models::Base
show all
- Defined in:
- lib/pandoru/models/_base.rb
Overview
Simple base model for Pandora API objects
Direct Known Subclasses
Bookmark, Collection, FocusTrait, GenreStation, PlaylistItem, SearchResultItem, SongFeedback, Station, StationFeedback, StationSeed, StationSeeds, TrackExplanation
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(data = {}, api_client = nil) ⇒ Base
Returns a new instance of Base.
35
36
37
38
|
# File 'lib/pandoru/models/_base.rb', line 35
def initialize(data = {}, api_client = nil)
@data = data
@api_client = api_client
end
|
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
7
8
9
|
# File 'lib/pandoru/models/_base.rb', line 7
def data
@data
end
|
Class Method Details
.date_field(name, json_key = nil) ⇒ Object
19
20
21
|
# File 'lib/pandoru/models/_base.rb', line 19
def self.date_field(name, json_key = nil)
field(name, json_key, type: :date)
end
|
.field(name, json_key = nil, type: nil, &block) ⇒ Object
13
14
15
16
17
|
# File 'lib/pandoru/models/_base.rb', line 13
def self.field(name, json_key = nil, type: nil, &block)
json_key ||= name.to_s
fields[name] = { json_key: json_key, type: type, formatter: block }
attr_accessor name
end
|
.fields ⇒ Object
9
10
11
|
# File 'lib/pandoru/models/_base.rb', line 9
def self.fields
@fields ||= {}
end
|
.from_json(api_client, data) ⇒ Object
23
24
25
26
27
28
|
# File 'lib/pandoru/models/_base.rb', line 23
def self.from_json(api_client, data)
return nil unless data
instance = new(data, api_client)
instance.populate_from_json(data)
instance
end
|
.from_json_list(api_client, data_list) ⇒ Object
30
31
32
33
|
# File 'lib/pandoru/models/_base.rb', line 30
def self.from_json_list(api_client, data_list)
return [] unless data_list
data_list.map { |data| from_json(api_client, data) }
end
|
Instance Method Details
#inspect ⇒ Object
73
74
75
76
77
78
79
|
# File 'lib/pandoru/models/_base.rb', line 73
def inspect
attrs = self.class.fields.keys.map do |name|
value = instance_variable_get("@#{name}")
"#{name}=#{value.inspect}"
end.join(' ')
"#<#{self.class.name} #{attrs}>"
end
|
#populate_from_json(data) ⇒ Object
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/pandoru/models/_base.rb', line 40
def populate_from_json(data)
self.class.fields.each do |name, config|
json_key = config[:json_key]
type = config[:type]
formatter = config[:formatter]
value = data[json_key]
value = case type
when :date
parse_date(value)
when :boolean
parse_boolean(value)
else
value
end
value = formatter.call(value) if formatter && value
instance_variable_set("@#{name}", value)
end
end
|
#to_h ⇒ Object
65
66
67
68
69
70
71
|
# File 'lib/pandoru/models/_base.rb', line 65
def to_h
hash = {}
self.class.fields.each do |name, _|
hash[name] = instance_variable_get("@#{name}")
end
hash
end
|