Class: Redd::Models::LazyModel
- Inherits:
-
BasicModel
- Object
- BasicModel
- Redd::Models::LazyModel
- Defined in:
- lib/redd/models/lazy_model.rb
Overview
The base class for lazily-initializable models.
Direct Known Subclasses
Comment, LiveThread, ModMail::Conversation, Multireddit, PrivateMessage, Submission, Subreddit, User, WikiPage
Instance Attribute Summary
Attributes inherited from BasicModel
Instance Method Summary collapse
-
#force_load ⇒ self
(also: #reload)
Force the object to make a request to reddit.
-
#initialize(client, base_attributes = {}) {|client| ... } ⇒ LazyModel
constructor
Create a lazily initialized class.
-
#method_missing(method_name, *args, &block) ⇒ Object
Return an attribute or raise a NoMethodError if it doesn’t exist.
-
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
Checks whether an attribute is supported by method_missing.
-
#to_h ⇒ Hash
Convert the object to a hash, making a request to fetch additional attributes if needed.
Methods inherited from BasicModel
Constructor Details
#initialize(client, base_attributes = {}) {|client| ... } ⇒ LazyModel
Create a lazily initialized class.
15 16 17 18 19 |
# File 'lib/redd/models/lazy_model.rb', line 15 def initialize(client, base_attributes = {}, &block) super(client, base_attributes) @lazy_loader = block @definitely_fully_loaded = false end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
Return an attribute or raise a NoMethodError if it doesn’t exist.
50 51 52 53 |
# File 'lib/redd/models/lazy_model.rb', line 50 def method_missing(method_name, *args, &block) ensure_fully_loaded unless @attributes.key?(method_name) super end |
Instance Method Details
#force_load ⇒ self Also known as: reload
Force the object to make a request to reddit.
23 24 25 26 27 28 |
# File 'lib/redd/models/lazy_model.rb', line 23 def force_load @attributes.merge!(@lazy_loader ? @lazy_loader.call(@client) : default_loader) @definitely_fully_loaded = true after_initialize self end |
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
Checks whether an attribute is supported by method_missing. Since we don’t know whether an attribute exists until we load it, we have to respond true until we load it.
43 44 45 |
# File 'lib/redd/models/lazy_model.rb', line 43 def respond_to_missing?(method_name, include_private = false) @definitely_fully_loaded ? super : true end |
#to_h ⇒ Hash
Convert the object to a hash, making a request to fetch additional attributes if needed.
33 34 35 36 |
# File 'lib/redd/models/lazy_model.rb', line 33 def to_h ensure_fully_loaded super end |