Module: Liquid::Utils

Defined in:
lib/liquid/utils.rb

Class Method Summary collapse

Class Method Details

.slice_collection(collection, from, to) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/liquid/utils.rb', line 3

def self.slice_collection(collection, from, to)
  if (from != 0 || !to.nil?) && collection.respond_to?(:load_slice)
    collection.load_slice(from, to)
  else
    slice_collection_using_each(collection, from, to)
  end
end

.slice_collection_using_each(collection, from, to) ⇒ Object



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

def self.slice_collection_using_each(collection, from, to)
  segments = []
  index = 0

  # Maintains Ruby 1.8.7 String#each behaviour on 1.9
  if collection.is_a?(String)
    return collection.empty? ? [] : [collection]
  end
  return [] unless collection.respond_to?(:each)

  collection.each do |item|
    if to && to <= index
      break
    end

    if from <= index
      segments << item
    end

    index += 1
  end

  segments
end

.to_date(obj) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/liquid/utils.rb', line 63

def self.to_date(obj)
  return obj if obj.respond_to?(:strftime)

  if obj.is_a?(String)
    return nil if obj.empty?
    obj = obj.downcase
  end

  case obj
  when 'now'.freeze, 'today'.freeze
    Time.now
  when /\A\d+\z/, Integer
    Time.at(obj.to_i)
  when String
    Time.parse(obj)
  end
rescue ::ArgumentError
  nil
end

.to_integer(num) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/liquid/utils.rb', line 36

def self.to_integer(num)
  return num if num.is_a?(Integer)
  num = num.to_s
  begin
    Integer(num)
  rescue ::ArgumentError
    raise Liquid::ArgumentError, "invalid integer"
  end
end

.to_number(obj) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/liquid/utils.rb', line 46

def self.to_number(obj)
  case obj
  when Float
    BigDecimal.new(obj.to_s)
  when Numeric
    obj
  when String
    (obj.strip =~ /\A-?\d+\.\d+\z/) ? BigDecimal.new(obj) : obj.to_i
  else
    if obj.respond_to?(:to_number)
      obj.to_number
    else
      0
    end
  end
end