Sha256: 9a9f3a1580e8fe8b9c7da475b26eb40a7ff82822c14f87deffa17fc95ae799ba

Contents?: true

Size: 1.44 KB

Versions: 34

Compression:

Stored size: 1.44 KB

Contents

module Builderator
  module Config
    ##
    # Extend Array with context about how its values should be merged with other
    # configuration layers. Possible modes are:
    #
    # * 'override' - Do not merge. Replace the other node's elements
    # * 'union' - Perform a set-union on the elements of this and the other node
    ##
    class List < Array
      class << self
        def coerce(somehting, options = {})
          return somehting if somehting.is_a?(self)
          return new(options).push(*somehting) if somehting.is_a?(Array)

          ## `somehting` is not a valid input. Just give back an instance.
          new([], options)
        end
      end

      attr_reader :mode

      def initialize(from = nil, **options)
        @mode = options.fetch(:mode, :union)

        merge!(from) unless from.nil?
      end

      def clone
        self.class.new(self, :mode => mode)
      end

      def set(*elements)
        clear
        push(*elements)
      end

      ##
      # Combine elements with `other` according to `other`'s `mode`
      ##
      def merge!(other)
        other = self.class.coerce(other)

        case other.mode
        when :override
          return false if self == other
          set(*other)

        when :union
          merged = self | other
          return false if merged == self

          set(*merged)

        else
          fail "Invalid List mode #{other.mode}!"
        end

        true
      end
    end
  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
builderator-1.1.6 lib/builderator/config/list.rb
builderator-1.1.5 lib/builderator/config/list.rb
builderator-1.1.4 lib/builderator/config/list.rb
builderator-1.1.3 lib/builderator/config/list.rb
builderator-1.1.2 lib/builderator/config/list.rb
builderator-1.1.1 lib/builderator/config/list.rb
builderator-1.1.0 lib/builderator/config/list.rb
builderator-1.0.4 lib/builderator/config/list.rb
builderator-1.0.3 lib/builderator/config/list.rb
builderator-1.0.2 lib/builderator/config/list.rb
builderator-1.0.1 lib/builderator/config/list.rb
builderator-1.0.0.pre.rc.12 lib/builderator/config/list.rb
builderator-1.0.0.pre.rc.11 lib/builderator/config/list.rb
builderator-1.0.0.pre.rc.10 lib/builderator/config/list.rb