Selectable
Note: Classes that include Selectable must also subclass Array
class Something < Array include Selectable end
Classes and Modules
Module Selectable::ObjectClass Selectable::SelectableError
Class Selectable::Tags
Class Selectable::TagsNotInitialized
Public class methods
Creates an alias for filter called +[]+, but only if [] doesn’t already exist in obj.
# File lib/selectable.rb, line 76 76: def self.included(obj) 77: alias_method :[], :filter unless obj.method_defined? :[] 78: end
Returns a Hash or Array
# 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
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.
# 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
# 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
Reverse filter.
# 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
# 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