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-2.1.1 lib/builderator/config/list.rb
builderator-2.1.0 lib/builderator/config/list.rb
builderator-2.0.4 lib/builderator/config/list.rb
builderator-2.0.3 lib/builderator/config/list.rb
builderator-2.0.2 lib/builderator/config/list.rb
builderator-2.0.1 lib/builderator/config/list.rb
builderator-2.0.0 lib/builderator/config/list.rb
builderator-1.3.2 lib/builderator/config/list.rb
builderator-1.3.1 lib/builderator/config/list.rb
builderator-1.3.0 lib/builderator/config/list.rb
builderator-1.2.3.pre.beta.1 lib/builderator/config/list.rb
builderator-1.2.2 lib/builderator/config/list.rb
builderator-1.2.1 lib/builderator/config/list.rb
builderator-1.2.0 lib/builderator/config/list.rb
builderator-1.1.12 lib/builderator/config/list.rb
builderator-1.1.11 lib/builderator/config/list.rb
builderator-1.1.10 lib/builderator/config/list.rb
builderator-1.1.9 lib/builderator/config/list.rb
builderator-1.1.8 lib/builderator/config/list.rb
builderator-1.1.7 lib/builderator/config/list.rb