Sha256: 7161f9451367bb71228e828131d7533f1e175c1eb7a73c01294a3ddb20aaef61

Contents?: true

Size: 1.37 KB

Versions: 59

Compression:

Stored size: 1.37 KB

Contents

module Workarea
  class SwappableList
    include Enumerable

    delegate :to_s, to: :@source

    def initialize(source = [])
      @source = Array(source)
    end

    def insert(index, new_val)
      index = assert_index(index, :before)
      @source.insert(index, new_val)
    end
    alias_method :insert_before, :insert

    def insert_after(index, new_val)
      index = assert_index(index, :after)
      insert(index + 1, new_val)
    end

    def swap(target, new_val)
      index = assert_index(target, :before)
      insert(index, new_val)
      @source.delete_at(index + 1)
    end

    def delete(target)
      @source.delete(target)
    end

    def +(other)
      self.class.new(
        @source + Array(other)
      )
    end

    def -(other)
      self.class.new(
        @source - Array(other)
      )
    end

    def method_missing(method, *args, &block)
      if @source.respond_to?(method)
        @source.send(method, *args, &block)
      else
        super
      end
    end

    def respond_to_missing?(method_name, include_private = false)
      super || @source.respond_to?(method_name)
    end

    def deep_dup
      self.class.new(@source.deep_dup)
    end

    private

    def assert_index(index, where)
      i = index.is_a?(Integer) ? index : @source.index(index)
      raise "No such list item to insert #{where}: #{index.inspect}" unless i
      i
    end
  end
end

Version data entries

59 entries across 59 versions & 1 rubygems

Version Path
workarea-core-3.5.27 lib/workarea/swappable_list.rb
workarea-core-3.5.26 lib/workarea/swappable_list.rb
workarea-core-3.4.45 lib/workarea/swappable_list.rb
workarea-core-3.5.25 lib/workarea/swappable_list.rb
workarea-core-3.5.23 lib/workarea/swappable_list.rb
workarea-core-3.4.44 lib/workarea/swappable_list.rb
workarea-core-3.5.22 lib/workarea/swappable_list.rb
workarea-core-3.4.43 lib/workarea/swappable_list.rb
workarea-core-3.5.21 lib/workarea/swappable_list.rb
workarea-core-3.4.42 lib/workarea/swappable_list.rb
workarea-core-3.5.20 lib/workarea/swappable_list.rb
workarea-core-3.4.41 lib/workarea/swappable_list.rb
workarea-core-3.5.19 lib/workarea/swappable_list.rb
workarea-core-3.4.40 lib/workarea/swappable_list.rb
workarea-core-3.5.18 lib/workarea/swappable_list.rb
workarea-core-3.4.39 lib/workarea/swappable_list.rb
workarea-core-3.5.17 lib/workarea/swappable_list.rb
workarea-core-3.4.38 lib/workarea/swappable_list.rb
workarea-core-3.5.16 lib/workarea/swappable_list.rb
workarea-core-3.4.37 lib/workarea/swappable_list.rb