class Redd::Models::LazyModel
The base class for lazily-initializable models.
Public Class Methods
Create a lazily initialized class. @param client [APIClient] the client that the model uses to make requests @param base_attributes [Hash] the already-known attributes that do not need to be looked up @yield [client] the model's client @yieldparam client [APIClient] @yieldreturn [Hash] the response of “initializing” the lazy model
Redd::Models::BasicModel::new
# 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
Public Instance Methods
Force the object to make a request to reddit. @return [self]
# 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
Return an attribute or raise a NoMethodError if it doesn't exist. @param method_name [Symbol] the name of the attribute @return [Object] the result of the attribute check
Redd::Models::BasicModel#method_missing
# 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
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. @param method_name [Symbol] the method name or attribute to check @param include_private [Boolean] whether to also include private methods @return [Boolean] whether the method is handled by method_missing
Redd::Models::BasicModel#respond_to_missing?
# File lib/redd/models/lazy_model.rb, line 43 def respond_to_missing?(method_name, include_private = false) @definitely_fully_loaded ? super : true end
Convert the object to a hash, making a request to fetch additional attributes if needed. @return [Hash]
Redd::Models::BasicModel#to_h
# File lib/redd/models/lazy_model.rb, line 33 def to_h ensure_fully_loaded super end
Private Instance Methods
@abstract A lazy loader to use when one is not provided.
# File lib/redd/models/lazy_model.rb, line 58 def default_loader {} end
Make sure the model is loaded at least once.
# File lib/redd/models/lazy_model.rb, line 63 def ensure_fully_loaded force_load unless @definitely_fully_loaded end
Gets the attribute and loads it if it may be available from the response.
Redd::Models::BasicModel#get_attribute
# File lib/redd/models/lazy_model.rb, line 68 def get_attribute(name) # XXX: Replace get_attribute calls with simple method calls? ensure_fully_loaded unless @attributes.key?(name) super end