Module: NestedFilters

Includes:
Liquid
Defined in:
lib/liquid_nested_sort/nested_filters.rb

Instance Method Summary collapse

Instance Method Details

#nested_sort(input, property = nil) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/liquid_nested_sort/nested_filters.rb', line 70

def nested_sort(input, property = nil)
  ary = InputIterator.new(input)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      LiquidUtils.nil_safe_compare(a, b)
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| LiquidUtils.nil_safe_compare(a[property], b[property]) }
    rescue TypeError
      raise Liquid::ArgumentError, "cannot select the property '#{property}'"
    end
  end
end

#nested_sort_natural(input, property = nil) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/liquid_nested_sort/nested_filters.rb', line 88

def nested_sort_natural(input, property = nil)
  ary = InputIterator.new(input)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      LiquidUtils.nil_safe_casecmp(a, b)
    end
  elsif property.include?('.') && LiquidUtils.nested_respond_to?(ary.first, property)
    ary.sort do |a, b|
      LiquidUtils.nil_safe_casecmp(LiquidUtils.nested_send(a, property), LiquidUtils.nested_send(b, property))
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| LiquidUtils.nil_safe_casecmp(a[property], b[property]) }
    rescue TypeError
      raise Liquid::ArgumentError, "cannot select the property '#{property}'"
    end
  end
end