Class: ClashOfClansApi::Models::Base
- Inherits:
-
Object
- Object
- ClashOfClansApi::Models::Base
- Defined in:
- lib/clash_of_clans_api/models/base.rb
Class Attribute Summary collapse
-
.required_fields ⇒ Object
readonly
Returns the value of attribute required_fields.
Class Method Summary collapse
Instance Method Summary collapse
- #[](key) ⇒ Object
- #cache_property(name, obj) ⇒ Object
-
#initialize(hash) ⇒ Base
constructor
A new instance of Base.
- #property_cached?(name) ⇒ Boolean
- #property_from_cache(name) ⇒ Object
- #to_h ⇒ Object
- #validate! ⇒ Object
Constructor Details
#initialize(hash) ⇒ Base
Returns a new instance of Base.
6 7 8 9 10 |
# File 'lib/clash_of_clans_api/models/base.rb', line 6 def initialize(hash) @hash = hash validate! end |
Class Attribute Details
.required_fields ⇒ Object (readonly)
Returns the value of attribute required_fields.
21 22 23 |
# File 'lib/clash_of_clans_api/models/base.rb', line 21 def required_fields @required_fields end |
Class Method Details
.property(name, key, type: nil, required: false) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/clash_of_clans_api/models/base.rb', line 23 def property(name, key, type: nil, required: false) define_method(name) do if type.nil? self[key] else if property_cached?(name) property_from_cache(name) else cache_property(name, self[key].then do |prop| prop.is_a?(Array) ? prop.map {|item| type.new(item) } : type.new(prop) end) end end end if required @required_fields = (@required_fields || [])+[key] end end |
Instance Method Details
#[](key) ⇒ Object
16 17 18 |
# File 'lib/clash_of_clans_api/models/base.rb', line 16 def [](key) @hash[key] end |
#cache_property(name, obj) ⇒ Object
48 49 50 51 52 |
# File 'lib/clash_of_clans_api/models/base.rb', line 48 def cache_property(name, obj) @property_cache ||= {} @property_cache[name] = obj end |
#property_cached?(name) ⇒ Boolean
44 45 46 |
# File 'lib/clash_of_clans_api/models/base.rb', line 44 def property_cached?(name) @property_cache && @property_cache.key?(name) end |
#property_from_cache(name) ⇒ Object
54 55 56 |
# File 'lib/clash_of_clans_api/models/base.rb', line 54 def property_from_cache(name) @property_cache[name] end |
#to_h ⇒ Object
12 13 14 |
# File 'lib/clash_of_clans_api/models/base.rb', line 12 def to_h @hash end |
#validate! ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/clash_of_clans_api/models/base.rb', line 58 def validate! if self.class.required_fields missing = self.class.required_fields.reject do |required_field| @hash.key?(required_field) end if missing.any? raise InvalidDataError, "The following keys are required, but missing from the model data: #{missing.map(&:inspect).join(', ')}" end end end |