Class: OrderedSet

Inherits:
BlankSlate show all
Defined in:
lib/ramaze/snippets/ordered_set.rb

Overview

Basically an Set, but with Order, ain’t that obivous?

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ OrderedSet

Create new instances, optionally pass the first set



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ramaze/snippets/ordered_set.rb', line 9

def initialize(*args)
  if args.size == 1
    @set = args.shift
  else
    @set = *args
  end

  @set ||= []
  @set = [@set] unless ::Array === @set
  @set.uniq!
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object

Delegate everything, but controlled, keep elements unique. Warning, this is not really atomic.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ramaze/snippets/ordered_set.rb', line 23

def method_missing(meth, *args, &block)
  case meth.to_s
  when /push|unshift|\<\</
    @set.delete(*args)
  when '[]='
    @set.map! do |e|
      if ::Array === args.last
        args.last.include?(e) ? nil : e
      else
        args.last == e ? nil : e
      end
    end
  end
  @set.__send__(meth, *args, &block)
ensure
  @set.compact! if meth == :[]=
end