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.4.27 lib/workarea/swappable_list.rb
workarea-core-3.5.4 lib/workarea/swappable_list.rb
workarea-core-3.4.26 lib/workarea/swappable_list.rb
workarea-core-3.5.3 lib/workarea/swappable_list.rb
workarea-core-3.4.25 lib/workarea/swappable_list.rb
workarea-core-3.5.2 lib/workarea/swappable_list.rb
workarea-core-3.4.24 lib/workarea/swappable_list.rb
workarea-core-3.5.1 lib/workarea/swappable_list.rb
workarea-core-3.4.23 lib/workarea/swappable_list.rb
workarea-core-3.4.22 lib/workarea/swappable_list.rb
workarea-core-3.5.0 lib/workarea/swappable_list.rb
workarea-core-3.4.21 lib/workarea/swappable_list.rb
workarea-core-3.5.0.beta.1 lib/workarea/swappable_list.rb
workarea-core-3.4.20 lib/workarea/swappable_list.rb
workarea-core-3.4.19 lib/workarea/swappable_list.rb
workarea-core-3.4.18 lib/workarea/swappable_list.rb
workarea-core-3.4.17 lib/workarea/swappable_list.rb
workarea-core-3.4.16 lib/workarea/swappable_list.rb
workarea-core-3.4.15 lib/workarea/swappable_list.rb