Class: MetalArchives::Base
- Inherits:
-
Object
- Object
- MetalArchives::Base
- Defined in:
- lib/metal_archives/models/base.rb
Overview
Abstract model class
Class Method Summary collapse
-
.cache(id) ⇒ Object
Generate cache key for id.
-
.properties ⇒ Object
Declared properties.
Instance Method Summary collapse
-
#==(other) ⇒ Object
Returns true if two objects have the same type and id.
-
#cached? ⇒ Boolean
Whether or not the object is currently cached.
-
#initialize(attributes = {}) ⇒ Base
constructor
Generic shallow copy constructor.
-
#inspect ⇒ Object
String representation.
-
#load! ⇒ Object
Fetch, parse and load the data.
-
#loaded? ⇒ Boolean
Whether or not the object is currently loaded.
-
#set(**attributes) ⇒ Object
Set properties.
Constructor Details
#initialize(attributes = {}) ⇒ Base
Generic shallow copy constructor
11 12 13 14 15 |
# File 'lib/metal_archives/models/base.rb', line 11 def initialize(attributes = {}) raise Errors::NotImplementedError, "no :id property in model" unless respond_to? :id set(**attributes) end |
Class Method Details
.cache(id) ⇒ Object
Generate cache key for id
100 101 102 |
# File 'lib/metal_archives/models/base.rb', line 100 def cache(id) "#{self.class.name}//#{id}" end |
.properties ⇒ Object
Declared properties
93 94 95 |
# File 'lib/metal_archives/models/base.rb', line 93 def properties @properties ||= {} end |
Instance Method Details
#==(other) ⇒ Object
Returns true if two objects have the same type and id
27 28 29 30 |
# File 'lib/metal_archives/models/base.rb', line 27 def ==(other) other.is_a?(self.class) && id == other.id end |
#cached? ⇒ Boolean
Whether or not the object is currently cached
63 64 65 |
# File 'lib/metal_archives/models/base.rb', line 63 def cached? loaded? && MetalArchives.cache.include?(self.class.cache(id)) end |
#inspect ⇒ Object
String representation
70 71 72 |
# File 'lib/metal_archives/models/base.rb', line 70 def inspect "#<#{self.class.name} @id=#{@id} @name=\"#{@name}\">" end |
#load! ⇒ Object
Fetch, parse and load the data
- Raises
-
Errors::InvalidIDError when no id
-
Errors::APIError when receiving a status code >= 400 (except 404)
39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/metal_archives/models/base.rb', line 39 def load! raise Errors::InvalidIDError, "no id present" unless id # Use constructor to set attributes set(**assemble) @loaded = true MetalArchives.cache[self.class.cache(id)] = self rescue StandardError => e # Don't cache invalid requests MetalArchives.cache.delete self.class.cache(id) raise e end |
#loaded? ⇒ Boolean
Whether or not the object is currently loaded
56 57 58 |
# File 'lib/metal_archives/models/base.rb', line 56 def loaded? @loaded ||= false end |
#set(**attributes) ⇒ Object
Set properties
20 21 22 |
# File 'lib/metal_archives/models/base.rb', line 20 def set(**attributes) attributes.each { |key, value| instance_variable_set(:"@#{key}", value) } end |