Class: Alchemy::ElementsFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/alchemy/elements_finder.rb

Overview

Loads elements from given page

Used by Page#find_elements and Alchemy::ElementsHelper#render_elements helper.

If you need custom element loading logic in your views you can create your own finder class and tell the Alchemy::ElementsHelper#render_elements helper or Page#find_elements to use that finder instead of this one.

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ElementsFinder

Returns a new instance of ElementsFinder.

Parameters:

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

    a customizable set of options

Options Hash (options):

  • :only (Array<String>|String)

    A list of element names to load only.

  • :except (Array<String>|String)

    A list of element names not to load.

  • :fixed (Boolean) — default: false

    Return only fixed elements

  • :count (Integer)

    The amount of elements to load

  • :offset (Integer)

    The offset to begin loading elements from

  • :random (Boolean) — default: false

    Randomize the output of elements

  • :reverse (Boolean) — default: false

    Reverse the load order

  • :fallback (Hash)

    Define elements that are loaded from another page if no element was found on given page.


31
32
33
# File 'lib/alchemy/elements_finder.rb', line 31

def initialize(options = {})
  @options = options
end

Instance Method Details

#elements(page:) ⇒ ActiveRecord::Relation

Parameters:

  • page (Alchemy::Page|String)

    The page the elements are loaded from. You can pass a page_layout String or a Page object.

Returns:

  • (ActiveRecord::Relation)

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/alchemy/elements_finder.rb', line 38

def elements(page:)
  elements = find_elements(page)

  if fallback_required?(elements)
    elements = elements.merge(fallback_elements)
  end

  if options[:reverse]
    elements = elements.reverse_order
  end

  if options[:random]
    elements = elements.reorder(Arel.sql(random_function))
  end

  elements.offset(options[:offset]).limit(options[:count])
end