Module Selectable
  1. lib/selectable/object.rb
  2. lib/selectable/tags.rb
  3. lib/selectable.rb
  4. show all

Selectable

Note: Classes that include Selectable must also subclass Array

class Something < Array
  include Selectable
end

Methods

public class

  1. included
  2. normalize

public instance

  1. filter
  2. filter!
  3. rfilter
  4. tags

Public class methods

included (obj)

Creates an alias for filter called +[]+, but only if [] doesn’t already exist in obj.

[show source]
    # File lib/selectable.rb, line 76
76:   def self.included(obj)
77:     alias_method :[], :filter unless obj.method_defined? :[]
78:   end
normalize (*tags)

Returns a Hash or Array

[show source]
    # File lib/selectable.rb, line 20
20:   def Selectable.normalize(*tags)
21:     tags.flatten!
22:     tags = tags.first if tags.first.kind_of?(Hash) || tags.first.kind_of?(Array)
23:     # NOTE: The string enforcement is disabled 
24:     # FOR NOW.
25:     #if tags.is_a?(Hash)
26:     #  #tmp = {}
27:     #  #tags.each_pair { |n,v| tmp[n] = v.to_s }
28:     #  #tags = tmp
29:     #else
30:     #  tags.collect! { |v| v.to_s }
31:     #end
32:     tags
33:   end

Public instance methods

filter (*tags)

Return the objects that match the given tags. This process is optimized for speed so there as few conditions as possible. One result of that decision is that it does not gracefully handle error conditions. For example, if the tags in an object have not been initialized, you will see this error:

undefined method `>=' for nil:NilClass

It also means you need be aware of the types of objects you are storing as values. If you store a Symbol, you must send a Symbol here.

[show source]
    # File lib/selectable.rb, line 48
48:   def filter(*tags)
49:     tags = Selectable.normalize tags
50:     # select returns an Array. We want a Selectable.
51:     items = self.select { |obj| obj.tags >= tags }
52:     self.class.new items
53:   end
filter! (*tags)
[show source]
    # File lib/selectable.rb, line 63
63:   def filter!(*tags)
64:     tags = Selectable.normalize tags
65:     self.delete_if { |obj|   obj.tags < tags }
66:   end
rfilter (*tags)

Reverse filter.

[show source]
    # File lib/selectable.rb, line 56
56:   def rfilter(*tags)
57:     tags = Selectable.normalize tags
58:     # select returns an Array. We want a Selectable.
59:     items = self.select { |obj| obj.tags < tags }
60:     self.class.new items
61:   end
tags ()
[show source]
    # File lib/selectable.rb, line 68
68:   def tags
69:     t = Selectable::Tags.new
70:     self.each { |o| t.merge o.tags }
71:     t
72:   end