Class: Amber::PageArray

Inherits:
Array
  • Object
show all
Defined in:
lib/amber/page_array.rb

Instance Method Summary collapse

Instance Method Details

#limit(num) ⇒ Object



10
11
12
# File 'lib/amber/page_array.rb', line 10

def limit(num)
  PageArray.new(self[0..(num-1)])
end

#order_by(attr, options = {}) ⇒ Object

available options:

:locale – the locale to use when comparing attributes :direction – either :asc or :desc :numeric – if true, attributes are cast as numbers before comparison



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/amber/page_array.rb', line 21

def order_by(attr, options={})
  locale = options[:locale] || I18n.locale
  direction = options[:direction] || :asc
  array = sort do |a,b|
    if direction == :desc
      a, b = b, a
    end
    a_prop = a.prop(locale, attr)
    b_prop = b.prop(locale, attr)
    if options[:numeric]
      a_prop = to_numeric(a_prop)
      b_prop = to_numeric(b_prop)
    end
    if a_prop.nil? && b_prop.nil?
      0
    elsif a_prop.nil?
      1
    elsif b_prop.nil?
      -1
    else
      a_prop <=> b_prop
    end
  end
  # remove pages from the results that have no value set for the attr
  array.delete_if do |page|
    page.prop(locale, attr).nil?
  end
  return PageArray.new.replace array
end

#to_numeric(anything) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/amber/page_array.rb', line 51

def to_numeric(anything)
  num = BigDecimal.new(anything.to_s)
  if num.frac == 0
    num.to_i
  else
    num.to_f
  end
end