Class: RSLT::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/rslt/rule.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stylesheet, selector, extensions, &block) ⇒ Rule

Returns a new instance of Rule.



6
7
8
9
10
11
# File 'lib/rslt/rule.rb', line 6

def initialize(stylesheet, selector, extensions, &block)
  @stylesheet = stylesheet
  @selector = selector
  @extensions = extensions
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



4
5
6
# File 'lib/rslt/rule.rb', line 4

def block
  @block
end

#elementObject (readonly)

Returns the value of attribute element.



4
5
6
# File 'lib/rslt/rule.rb', line 4

def element
  @element
end

#selectorObject (readonly)

Returns the value of attribute selector.



4
5
6
# File 'lib/rslt/rule.rb', line 4

def selector
  @selector
end

#stylesheetObject (readonly)

Returns the value of attribute stylesheet.



4
5
6
# File 'lib/rslt/rule.rb', line 4

def stylesheet
  @stylesheet
end

Instance Method Details

#applies_to_element?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/rslt/rule.rb', line 18

def applies_to_element?
  matching_elements(element.document).include? element
end

#generate(builder) ⇒ Object



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

def generate(builder)
  # Call the block in the elements context
  wrapper = ElementWrapper.new(stylesheet, element, builder)
  @extensions.each {|e| wrapper.extend e }
  wrapper.instance_eval(&@block)
rescue Exception => e
  if e.message =~ /With selector '.*' and included modules/
    raise e
  else
    raise e.class, "With selector '#{selector}' and included modules: #{@extensions.inspect}\n#{e.message}\n#{e.backtrace.join("\n")}"
  end
end

#matches?(element) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
# File 'lib/rslt/rule.rb', line 22

def matches?(element)
  @element = element
  if applies_to_element?
    self # if it matches, nil otherwise
  else
    nil
  end
end

#matching_elements(document) ⇒ Object



13
14
15
16
# File 'lib/rslt/rule.rb', line 13

def matching_elements(document)
  @selector_cache ||= {}
  @selector_cache[document] ||= document.css(@selector)
end