Sha256: 9f3d541c10a3995186d2bcbecc5dda7b0bf040ae962bcd6d0b4045025a3f9621

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

# 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
        raise 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
      Array @input.split(LIST_SPLIT)
        .map(&:strip)
    end

    def split_range
      Array @input.split(RANGE_SPLIT)
        .map(&:strip)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
monetize-1.3.1 lib/collection.rb