Sha256: e1e63e1b0df2c183b4913809e126e539748a4f8b57ab2559ee53ef730892ed74

Contents?: true

Size: 1.9 KB

Versions: 138

Compression:

Stored size: 1.9 KB

Contents

module Eco
  module Data
    class Mapper

      # it expects [[v1a, v1b], [v2a, v2b] ...]
      def initialize (array_of_arrays = [], internal: :last)
        @internal_order = internal
        @source         = array_of_arrays

        if @source
          # internal should be always last in @source
          @source = @source.map { |a| a.reverse } unless internal == :last

          # first declarations take priority
          @by_external = @source.reverse.to_h
          @by_internal = @source.reverse.map do |pair|
            pair.reverse
          end.to_h
        end
      end

      def as_json(internal: @internal_order)
        to_a(internal: internal)
      end

      def to_json(internal: @internal_order)
        content = as_json(internal: internal).map do |pair|
          "  " + pair.to_json
        end.join(",\n")
        "[\n#{content}\n]"
      end

      def to_a(internal: @internal_order)
        @by_internal.map do |int, ext|
          internal == :last ? [ext, int] : [int, ext]
        end
      end

      def +(array_of_arrays)
        self.class.new(array_of_arrays + to_a, internal: @internal_order)
      end

      def list(type = :internal)
        return [] if !@source
        @source.map do |pair|
          type == :internal ? pair.last : pair.first
        end.uniq
      end

      def internal?(value)
        return true if !@source
        @by_internal.key?(value)
      end

      def external?(value)
        return true if !@source
        @by_external.key?(value)
      end

      def include?(value)
        return true if !@source
        internal?(value) || external?(value)
      end

      def to_internal(value)
        return value if !@source
        @by_external[value]
      end

      def to_external(value)
        return value if !@source
        @by_internal[value]
      end

    end
  end
end

Version data entries

138 entries across 138 versions & 1 rubygems

Version Path
eco-helpers-2.5.10 lib/eco/data/mapper.rb
eco-helpers-2.5.9 lib/eco/data/mapper.rb
eco-helpers-2.5.8 lib/eco/data/mapper.rb
eco-helpers-2.5.7 lib/eco/data/mapper.rb
eco-helpers-2.5.6 lib/eco/data/mapper.rb
eco-helpers-2.5.5 lib/eco/data/mapper.rb
eco-helpers-2.5.4 lib/eco/data/mapper.rb
eco-helpers-2.5.3 lib/eco/data/mapper.rb
eco-helpers-2.5.2 lib/eco/data/mapper.rb
eco-helpers-2.5.1 lib/eco/data/mapper.rb
eco-helpers-2.4.9 lib/eco/data/mapper.rb
eco-helpers-2.4.8 lib/eco/data/mapper.rb
eco-helpers-2.4.7 lib/eco/data/mapper.rb
eco-helpers-2.4.6 lib/eco/data/mapper.rb
eco-helpers-2.4.5 lib/eco/data/mapper.rb
eco-helpers-2.4.4 lib/eco/data/mapper.rb
eco-helpers-2.4.3 lib/eco/data/mapper.rb
eco-helpers-2.4.2 lib/eco/data/mapper.rb
eco-helpers-2.3.3 lib/eco/data/mapper.rb
eco-helpers-2.3.2 lib/eco/data/mapper.rb