Module: Selectable

Included in:
Benelux::Stats::Group, Benelux::Timeline, SelectableArray, SelectableHash
Defined in:
lib/selectable.rb,
lib/selectable/tags.rb,
lib/selectable/object.rb

Overview

Selectable

<strong>Note: Classes that include Selectable must also subclass Array</strong>

class Something < Array
  include Selectable
end

Defined Under Namespace

Modules: Object Classes: SelectableError, Tags, TagsNotInitialized

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(obj) ⇒ Object

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



76
77
78
# File 'lib/selectable.rb', line 76

def self.included(obj)
  alias_method :[], :filter unless obj.method_defined? :[]
end

.normalize(*tags) ⇒ Object

Returns a Hash or Array



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/selectable.rb', line 20

def Selectable.normalize(*tags)
  tags.flatten!
  tags = tags.first if tags.first.kind_of?(Hash) || tags.first.kind_of?(Array)
  # NOTE: The string enforcement is disabled 
  # FOR NOW.
  #if tags.is_a?(Hash)
  #  #tmp = {}
  #  #tags.each_pair { |n,v| tmp[n] = v.to_s }
  #  #tags = tmp
  #else
  #  tags.collect! { |v| v.to_s }
  #end
  tags
end

Instance Method Details

#filter(*tags) ⇒ Object

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.



48
49
50
51
52
53
# File 'lib/selectable.rb', line 48

def filter(*tags)
  tags = Selectable.normalize tags
  # select returns an Array. We want a Selectable.
  items = self.select { |obj| obj.tags >= tags }
  self.class.new items
end

#filter!(*tags) ⇒ Object



63
64
65
66
# File 'lib/selectable.rb', line 63

def filter!(*tags)
  tags = Selectable.normalize tags
  self.delete_if { |obj|   obj.tags < tags }
end

#rfilter(*tags) ⇒ Object

Reverse filter.



56
57
58
59
60
61
# File 'lib/selectable.rb', line 56

def rfilter(*tags)
  tags = Selectable.normalize tags
  # select returns an Array. We want a Selectable.
  items = self.select { |obj| obj.tags < tags }
  self.class.new items
end

#tagsObject



68
69
70
71
72
# File 'lib/selectable.rb', line 68

def tags
  t = Selectable::Tags.new
  self.each { |o| t.merge o.tags }
  t
end