Class: SimpleSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_selector.rb,
lib/simple_selector/segment.rb,
lib/simple_selector/version.rb,
lib/simple_selector/specificity.rb

Defined Under Namespace

Classes: Segment, Specificity

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string = nil) ⇒ SimpleSelector

Returns a new instance of SimpleSelector.



8
9
10
11
12
# File 'lib/simple_selector.rb', line 8

def initialize(string=nil)
  @segments = []
  @specificity = Specificity.new
  concat(string) unless string.nil?
end

Instance Attribute Details

#specificityObject (readonly)

Returns the value of attribute specificity.



14
15
16
# File 'lib/simple_selector.rb', line 14

def specificity
  @specificity
end

Instance Method Details

#+(string) ⇒ Object



24
25
26
# File 'lib/simple_selector.rb', line 24

def +(string)
  duplicate.concat(string)
end

#==(other) ⇒ Object



56
57
58
# File 'lib/simple_selector.rb', line 56

def ==(other)
  to_s == other.to_s
end

#concat(string) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/simple_selector.rb', line 16

def concat(string)
  string.scan(/[\w.#]+/).map { |s| Segment.new(s) }.each do |segment|
    @segments << segment
    @specificity += segment.specificity
  end
  self
end

#duplicateObject



60
61
62
63
64
65
# File 'lib/simple_selector.rb', line 60

def duplicate
  d = dup
  d.instance_variable_set(   "@segments",    @segments.dup)
  d.instance_variable_set("@specificity", @specificity.dup)
  d
end

#empty?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/simple_selector.rb', line 44

def empty?
  @segments.none?
end

#inspectObject



52
53
54
# File 'lib/simple_selector.rb', line 52

def inspect
  "#<#{self.class} #{to_s.inspect}>"
end

#match?(tag) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/simple_selector.rb', line 28

def match?(tag)
  return true  if @segments.none?
  return false unless @segments.last.match?(tag)

  index = @segments.size - 2
  current_tag = tag

  while index >= 0 && current_tag = current_tag.parent
    if @segments[index].match?(current_tag)
      index -= 1
      next
    end
  end
  index == -1
end

#to_sObject



48
49
50
# File 'lib/simple_selector.rb', line 48

def to_s
  @segments.map { |segment| segment.to_s }.join(" ")
end