Sha256: 171b2d5267523428e904501949804d51eef80e69b78652d868137a38074a8397

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

require "active_support/core_ext/module/delegation"
require "active_support/core_ext/array"
require "active_support/core_ext/object"

module SimpleTaggable
  class TagList
    include Enumerable

    delegate \
      :[],
      :each,
      :length,
      :size,
      :count,
      :include?,
      :empty?,
      :clear,
      :to_s,
      to: :raw_data

    class << self
      def [](*tags)
        new(*tags)
      end
    end

    def initialize(*tags, filters: [], converters: [])
      @raw_data = []

      @filters = filters.freeze
      @converters = converters.freeze

      tags.flatten.each do |tag|
        if tag.is_a?(TagList)
          tag.each { |t| add(t) }
        else
          add(tag)
        end
      end
    end

    def add(*tags)
      tags.flatten.each do |t|
        tag = @converters.inject(t.to_s) do |pre_tag, converter|
          converter.call(self, pre_tag)
        end

        if @filters.all? { |filter| filter.call(self, tag) }
          tag.freeze
          @raw_data << tag
        end
      end
      @raw_data.uniq!

      self
    end
    alias :<< :add

    def to_a
      @raw_data.deep_dup
    end

    def inspect
      "SimpleTaggable::TagList#{raw_data.inspect}"
    end

    private

    def raw_data
      @raw_data
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
simple_taggable-1.0.1 lib/simple_taggable/tag_list.rb
simple_taggable-1.0.0 lib/simple_taggable/tag_list.rb