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-1.3.19 lib/eco/data/mapper.rb
eco-helpers-1.4.1 lib/eco/data/mapper.rb
eco-helpers-1.4.0 lib/eco/data/mapper.rb
eco-helpers-1.3.18 lib/eco/data/mapper.rb
eco-helpers-1.3.17 lib/eco/data/mapper.rb
eco-helpers-1.3.16 lib/eco/data/mapper.rb
eco-helpers-1.3.15 lib/eco/data/mapper.rb
eco-helpers-1.3.14 lib/eco/data/mapper.rb
eco-helpers-1.3.13 lib/eco/data/mapper.rb
eco-helpers-1.3.12 lib/eco/data/mapper.rb
eco-helpers-1.3.11 lib/eco/data/mapper.rb
eco-helpers-1.3.10 lib/eco/data/mapper.rb
eco-helpers-1.3.9 lib/eco/data/mapper.rb
eco-helpers-1.3.8 lib/eco/data/mapper.rb
eco-helpers-1.3.7 lib/eco/data/mapper.rb
eco-helpers-1.3.6 lib/eco/data/mapper.rb
eco-helpers-1.3.5 lib/eco/data/mapper.rb
eco-helpers-1.3.4 lib/eco/data/mapper.rb