lib/deface/applicator.rb in deface-0.8.0 vs lib/deface/applicator.rb in deface-0.9.0
- old
+ new
@@ -22,10 +22,12 @@
if override.disabled?
Rails.logger.info("\e[1;32mDeface:\e[0m '#{override.name}' is disabled") if log
next
end
+ override.parsed_document = doc
+
if override.end_selector.blank?
# single css selector
matches = doc.css(override.selector)
@@ -116,19 +118,16 @@
end
end
else
+ unless [:remove, :replace, :replace_contents, :surround, :surround_contents].include? override.action
+ raise Deface::NotSupportedError, ":#{override.action} action does not support :closing_selector"
+ end
# targeting range of elements as end_selector is present
- starting = doc.css(override.selector).first
+ starting, ending = select_endpoints(doc, override.selector, override.end_selector)
- if starting && starting.parent
- ending = starting.parent.css(override.end_selector).first
- else
- ending = doc.css(override.end_selector).first
- end
-
if starting && ending
if log
Rails.logger.info("\e[1;32mDeface:\e[0m '#{override.name}' matched starting with '#{override.selector}' and ending with '#{override.end_selector}'")
end
@@ -141,10 +140,47 @@
starting.before(override.source_element)
elements.map &:remove
when :replace_contents
elements[1..-2].map &:remove
starting.after(override.source_element)
+ when :surround, :surround_contents
+
+ new_source = override.source_element.clone(1)
+
+ if original = new_source.css("code:contains('render_original')").first
+
+ if override.action == :surround
+ start = elements[0].clone(1)
+ original.replace start
+
+ elements[1..-1].each do |element|
+ element = element.clone(1)
+ start.after element
+ start = element
+ end
+
+ starting.before(new_source)
+ elements.map &:remove
+
+
+ elsif override.action == :surround_contents
+
+ start = elements[1].clone(1)
+ original.replace start
+
+ elements[2...-1].each do |element|
+ element = element.clone(1)
+ start.after element
+ start = element
+ end
+
+ starting.after(new_source)
+ elements[1...-1].map &:remove
+ end
+ else
+ #maybe we should log that the original wasn't found.
+ end
end
else
if starting.nil?
Rails.logger.info("\e[1;32mDeface:\e[0m '#{override.name}' failed to match with starting selector '#{override.selector}'")
else
@@ -165,28 +201,42 @@
end
source
end
- private
+
+ def select_endpoints(doc, start, finish)
+ # targeting range of elements as end_selector is present
+ #
+ finish = "#{start} ~ #{finish}"
+ starting = doc.css(start).first
+
+ ending = if starting && starting.parent
+ starting.parent.css(finish).first
+ else
+ doc.css(finish).first
+ end
+
+ return starting, ending
+
+ end
+
# finds all elements upto closing sibling in nokgiri document
#
def select_range(first, last)
first == last ? [first] : [first, *select_range(first.next, last)]
end
+ private
+
def normalize_attribute_name(name)
name = name.to_s.gsub /"|'/, ''
if /\Adata-erb-/ =~ name
name.gsub! /\Adata-erb-/, ''
end
name
- end
-
- def set_attributes(match, name, value)
-
end
end
end
end