Class: Selectable::Tags

Inherits:
Hash
  • Object
show all
Defined in:
lib/selectable/tags.rb

Overview

An example of filtering an Array of tagged objects based on a provided Hash of tags or Array of tag values. obj in this case would be an object that includes Taggable.

class Something
  def [](tags={})
    tags = [tags].flatten unless tags.is_a?(Hash)
    self.select do |obj|
      obj.tags >= tags
    end
  end
end

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args) ⇒ Object (private)

Raises:



80
81
82
# File 'lib/selectable/tags.rb', line 80

def method_missing(meth, *args)
  raise SelectableError, "#{meth}: #{args.first} is not a Hash or Array #{self}"
end

Instance Method Details

#<(other) ⇒ Object



61
# File 'lib/selectable/tags.rb', line 61

def <(other)  (self <=> other)  < 0 end

#<=(other) ⇒ Object



63
# File 'lib/selectable/tags.rb', line 63

def <=(other) (self <=> other) <= 0 end

#<=>(b) ⇒ Object

Comparison between other Hash and Array objects.

e.g.

a = {:a => 1, :b => 2}
a > {:a => 1, :b => 2, :c => 3}    # => false
a > {:a => 1}                      # => true
a < {:a => 1, :b => 2, :c => 3}    # => true
a >= [2, 1]                        # => true
a > [2, 1]                         # => false


55
56
57
58
# File 'lib/selectable/tags.rb', line 55

def <=>(b)
  return 0 if self == b
  self.send :"compare_#{b.class}", b
end

#==(other) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/selectable/tags.rb', line 32

def ==(other)
  if other.is_a?(Array)
    # NOTE: This resolves the issue of sorting an Array
    # with a mix of Object types (Integers, Strings, Symbols).
    # As in: self.values.sort == other.sort)
    (self.values.size == other.size) &&
    (self.values - other).empty?
  else
    super(other)
  end
end

#>(other) ⇒ Object



60
# File 'lib/selectable/tags.rb', line 60

def >(other)  (self <=> other)  > 0 end

#>=(other) ⇒ Object



64
# File 'lib/selectable/tags.rb', line 64

def >=(other) (self <=> other) >= 0 end

#inspectObject



28
29
30
# File 'lib/selectable/tags.rb', line 28

def inspect
  to_s
end

#to_sObject



20
21
22
23
24
25
26
# File 'lib/selectable/tags.rb', line 20

def to_s
  tagstr = []
  self.each_pair do |n,v|
    tagstr << "%s=%s" % [n,v]
  end
  tagstr.join ' '
end