Class: Redd::Models::LazyModel

Inherits:
BasicModel show all
Defined in:
lib/redd/models/lazy_model.rb

Overview

The base class for lazily-initializable models.

Instance Attribute Summary

Attributes inherited from BasicModel

#client

Instance Method Summary collapse

Methods inherited from BasicModel

from_id, #inspect, #to_ary

Constructor Details

#initialize(client, base_attributes = {}) {|client| ... } ⇒ LazyModel

Create a lazily initialized class.

Parameters:

  • client (APIClient)

    the client that the model uses to make requests

  • base_attributes (Hash) (defaults to: {})

    the already-known attributes that do not need to be looked up

Yields:

  • (client)

    the model’s client

Yield Parameters:

Yield Returns:

  • (Hash)

    the response of “initializing” the lazy model



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.

Parameters:

  • method_name (Symbol)

    the name of the attribute

Returns:

  • (Object)

    the result of the attribute check



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_loadself Also known as: reload

Force the object to make a request to reddit.

Returns:

  • (self)


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.

Parameters:

  • method_name (Symbol)

    the method name or attribute to check

  • include_private (Boolean) (defaults to: false)

    whether to also include private methods

Returns:

  • (Boolean)

    whether the method is handled by method_missing



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_hHash

Convert the object to a hash, making a request to fetch additional attributes if needed.

Returns:

  • (Hash)


33
34
35
36
# File 'lib/redd/models/lazy_model.rb', line 33

def to_h
  ensure_fully_loaded
  super
end