forked from RubyMoney/monetize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collection.rb
57 lines (44 loc) · 1.15 KB
/
collection.rb
1
2
3
4
5
6
7
8
9
10
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# encoding: utf-8
require 'monetize'
require 'forwardable'
module Monetize
class Collection
extend Forwardable
include Enumerable
def_delegators :@list, :[], :each, :last
attr_reader :input, :currency, :options
def self.parse(input, currency = Money.default_currency, options = {})
new(input, currency, options).parse
end
def initialize(input, currency = Money.default_currency, options = {})
if input.respond_to? :strip
@input = input.clone.strip
else
fail ArgumentError, 'Input must be a string'
end
@currency = currency
@options = options
@list = []
end
def parse
if range?
@list = split_range.map { |fragment| Monetize.parse(fragment, currency, options) }
else
@list = split_list.map { |fragment| Monetize.parse(fragment, currency, options) }
end
self
end
def range?
RANGE_SPLIT =~ input
end
private
LIST_SPLIT = %r{[/,]}
RANGE_SPLIT = /-/
def split_list
@input.split(LIST_SPLIT).map(&:strip)
end
def split_range
@input.split(RANGE_SPLIT).map(&:strip)
end
end
end