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.0.45 lib/eco/data/mapper.rb
eco-helpers-2.0.44 lib/eco/data/mapper.rb
eco-helpers-2.0.43 lib/eco/data/mapper.rb
eco-helpers-2.0.42 lib/eco/data/mapper.rb
eco-helpers-2.0.41 lib/eco/data/mapper.rb
eco-helpers-2.0.40 lib/eco/data/mapper.rb
eco-helpers-2.0.39 lib/eco/data/mapper.rb
eco-helpers-2.0.38 lib/eco/data/mapper.rb
eco-helpers-2.0.37 lib/eco/data/mapper.rb
eco-helpers-2.0.36 lib/eco/data/mapper.rb
eco-helpers-2.0.35 lib/eco/data/mapper.rb
eco-helpers-2.0.34 lib/eco/data/mapper.rb
eco-helpers-2.0.33 lib/eco/data/mapper.rb
eco-helpers-2.0.32 lib/eco/data/mapper.rb
eco-helpers-2.0.31 lib/eco/data/mapper.rb
eco-helpers-2.0.30 lib/eco/data/mapper.rb
eco-helpers-2.0.29 lib/eco/data/mapper.rb
eco-helpers-2.0.28 lib/eco/data/mapper.rb
eco-helpers-2.0.27 lib/eco/data/mapper.rb
eco-helpers-2.0.26 lib/eco/data/mapper.rb