Sha256: 4db94b4d3b63a9725c52bcf7729003a92f3d7b15a84d5f3637d3b414e97532f5

Contents?: true

Size: 1.37 KB

Versions: 9

Compression:

Stored size: 1.37 KB

Contents

module EDTF

  class Set
    extend Forwardable

    include Enumerable
    include Comparable

    def_delegators :@dates, :size, :length, :empty?
    def_delegators :to_a, :include?

    attr_accessor :choice, :later, :earlier


    def initialize(*dates)
      @dates = ::Set.new(dates.flatten)
      @choice, @later, @earlier = false, false, false
    end

    def initialize_copy(other)
      @set = other.to_set
    end

    [:choice, :later, :earlier].each do |m|
      define_method("#{m}?") { send(m) }
      define_method("#{m}!") do
        send("#{m}=", true)
        self
      end
    end

    def <<(date)
      dates << date
      self
    end

    def each
      if block_given?
        to_a.each(&Proc.new)
        self
      else
        to_enum
      end
    end

    def edtf
      parenthesize(dates.map { |d|
        d.respond_to?(:edtf) ? d.edtf : d.to_s
      }.sort.join(','))
    end

    def to_a
      dates.map { |d| Array(d) }.flatten.sort
    end

    def to_set
      to_a.to_set
    end

    alias to_s edtf

    def <=>(other)
      return nil unless other.respond_to?(:to_a)
      to_a <=> other.to_a
    end

    protected

    attr_reader :dates

    private

    def parenthesize(string)
      p = choice? ? %w([ ]) : %w({ })
      p[-1,0] = '..' if earlier?
      p[-1,0] = string unless string.empty?
      p[-1,0] = '..' if later?
      p.join
    end

  end

end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
edtf-3.0.5 lib/edtf/set.rb
edtf-3.0.4 lib/edtf/set.rb
edtf-3.0.3 lib/edtf/set.rb
edtf-3.0.2 lib/edtf/set.rb
edtf-3.0.1 lib/edtf/set.rb
edtf-3.0.0 lib/edtf/set.rb
edtf-2.3.1 lib/edtf/set.rb
edtf-2.3.0 lib/edtf/set.rb
edtf-2.2.0 lib/edtf/set.rb