class Onsi::Includes

Used to include other objects in a root Resource objects.

@example

def index
  @person = Person.find(params[:person_id])
  @email = @person.emails.find(params[:id])
  @includes = Onsi::Includes.new(params[:include])
  @includes.fetch_person { @person }
  @includes.fetch_messages { @email.messages }
  render_resource(Onsi::Resource.new(@email, params[:version].to_sym, includes: @includes))
end

Constants

FETCH_METHOD_REGEXP

The fetch method matcher regex

@private

Attributes

included[R]

The includes

@return [Array<Symbol>]

Public Class Methods

new(included) click to toggle source

Create a new Includes object.

@param included [String, Enumerable<String, Symbol>, nil] The keys to be

included.

@return [Onsi::Includes]

# File lib/onsi/includes.rb, line 34
def initialize(included)
  @included = parse_included(included)
end

Public Instance Methods

load_included() click to toggle source

Load all included resources.

@private

# File lib/onsi/includes.rb, line 62
def load_included
  @load_included ||= {}.tap do |root|
    included.each do |name|
      fetcher = fetch_methods[name]
      next if fetcher.nil?

      results = fetcher.call
      root[name] = results
    end
  end
end
method_missing(name, *args, &block) click to toggle source

@private

Calls superclass method
# File lib/onsi/includes.rb, line 40
def method_missing(name, *args, &block)
  if name =~ FETCH_METHOD_REGEXP
    add_fetch_method(name.to_s.gsub(/\Afetch_/, ''), *args, &block)
  else
    super
  end
end
respond_to_missing?(name, include_private = false) click to toggle source

@private

Calls superclass method
# File lib/onsi/includes.rb, line 50
def respond_to_missing?(name, include_private = false)
  if name =~ FETCH_METHOD_REGEXP
    true
  else
    super
  end
end

Private Instance Methods

add_fetch_method(name, &block) click to toggle source
# File lib/onsi/includes.rb, line 80
def add_fetch_method(name, &block)
  if block.nil?
    raise ArgumentError, "Must specify a block for fetch_#{name}"
  end

  fetch_methods[name.to_sym] = block
end
fetch_methods() click to toggle source
# File lib/onsi/includes.rb, line 76
def fetch_methods
  @fetch_methods ||= {}
end
parse_included(included) click to toggle source
# File lib/onsi/includes.rb, line 88
def parse_included(included)
  case included
  when Enumerable
    included.map(&:to_sym)
  when String
    included.split(',').map(&:to_sym)
  when Symbol
    Array(included)
  when nil
    []
  else
    raise ArgumentError, "Onsi::Includes unknown included type #{included}"
  end
end