Class: Listpress::DefaultResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/listpress/default_resolver.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, listing) ⇒ DefaultResolver

Returns a new instance of DefaultResolver.



5
6
7
8
# File 'lib/listpress/default_resolver.rb', line 5

def initialize(collection, listing)
  @collection = collection
  @listing = listing
end

Instance Attribute Details

#listingObject (readonly)

Returns the value of attribute listing.



3
4
5
# File 'lib/listpress/default_resolver.rb', line 3

def listing
  @listing
end

Instance Method Details

#collectionObject



65
66
67
# File 'lib/listpress/default_resolver.rb', line 65

def collection
  @_collection_cache ||= page(sort(filter(@collection)))
end

#filter(collection) ⇒ Object

apply filters to collection



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/listpress/default_resolver.rb', line 11

def filter(collection)
  # skip filters if we need to retrieve a specific item
  return collection.where(id: listing.params[:item_id]) if listing.params[:item_id]

  listing.filters.each do |filter|
    val = listing.filter_value(filter[:name])

    next if val.nil? || val == ""  # beware of false (valid filter value)

    if filter[:proc]
      collection = filter[:proc].call(collection, val)
    elsif filter[:method]
      collection = collection.public_send(filter[:method], val)
    elsif filter[:column]
      collection = collection.where(filter[:column] => val)
    else
      if collection.respond_to?(filter[:name]) && !collection.model.column_names.include?(filter[:name].to_s)
        collection = collection.public_send(filter[:name], val)
      elsif
      collection = collection.where(filter[:name] => val)
      end
    end
  end

  collection
end

#page(collection) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/listpress/default_resolver.rb', line 57

def page(collection)
  if listing.paginate? && !listing.item_refresh?
    collection = collection.paginate(page: listing.params[:page] || 1, per_page: listing.options[:per_page])
  end

  collection
end

#sort(collection) ⇒ Object

apply sort to collection



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

def sort(collection)
  attr, dir = listing.sort
  if attr && column = listing.columns.detect {|c| c[:attr] == attr}
    case column[:sort]
    when true
      collection = collection.order(attr => dir)
    when Symbol, String
      collection = collection.order(column[:sort] => dir)
    when Hash
      collection = collection.order(column[:sort][dir] || (raise ArgumentError, "When using hash as a :sort option for a column, :asc and :desc keys are expected."))
    else
      # do not sort
    end
  end

  collection
end