Module: Rusty::RuleSet
- Includes:
- Helpers
- Defined in:
- lib/rusty/rule_set.rb
Overview
This file is part of the rusty ruby gem.
Copyright © 2013 @radiospiel Distributed under the terms of the modified BSD license, see LICENSE.BSD
Defined Under Namespace
Classes: Rule
Instance Method Summary collapse
-
#after(*selectors, &block) ⇒ Object
record a rule for any of these selectors.
-
#best_rule(mode, node) ⇒ Object
return the best matching rule for a given node Mode should be :on or :after.
-
#on(*selectors, &block) ⇒ Object
record a rule for any of these selectors.
-
#transform!(node, scope = nil) ⇒ Object
transform a node, and return transformed data.
Methods included from Helpers
Instance Method Details
#after(*selectors, &block) ⇒ Object
record a rule for any of these selectors.
This rule will be activated when a node’s processing is done.
Note: The after method is similar to
on "selector" do
callback do
do_something
end
end
31 32 33 |
# File 'lib/rusty/rule_set.rb', line 31 def after(*selectors, &block) register_rule(:after, *selectors, &block) end |
#best_rule(mode, node) ⇒ Object
return the best matching rule for a given node Mode should be :on or :after
61 62 63 64 65 66 |
# File 'lib/rusty/rule_set.rb', line 61 def best_rule(mode, node) rules_for_mode(mode).values. select { |rule| rule.selector.match?(node) }. sort_by { |rule| rule.selector.weight }. last end |
#on(*selectors, &block) ⇒ Object
record a rule for any of these selectors.
This rule will be activated when a node gets processed.
16 17 18 |
# File 'lib/rusty/rule_set.rb', line 16 def on(*selectors, &block) register_rule(:on, *selectors, &block) end |
#transform!(node, scope = nil) ⇒ Object
transform a node, and return transformed data.
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/rusty/rule_set.rb', line 82 def transform!(node, scope = nil) if node.is_a?(Nokogiri::XML::Document) node = node.root end scope ||= Rusty::Scope.new(node) # The callback scope for this node. callback_binding = callback_binding_klass.new(scope) has_rule = false [ :on, :after ].each do |mode| # find explicit rule for this node. Warn if there is none. if rule = best_rule(mode, node) has_rule = true callback_binding.instance_eval(&rule.proc) end # in :on mode: process children, unless explicitely skipped. if mode == :on && !callback_binding.skip? node.children.each do |child| next if child.text? || child.cdata? next if child.comment? transform! child, Rusty::Scope.new(child, scope) end end # run callback if callback = callback_binding.callback callback_binding.instance_eval(&callback) end end unless has_rule path = node.self_and_parents.map(&:simplified_name).join(" > ") STDERR.puts "no rule registered: #{path}" end scope end |