Sha256: c451ced8b03b10bbb76a1380b4ed4036d92b02baad306942052714836fea7120
Contents?: true
Size: 1.82 KB
Versions: 3
Compression:
Stored size: 1.82 KB
Contents
module CrazyHarry module Change BLOCK_CONVERSION_ELEMENTS = { inlines: %w(br), blocks: %w(div p) } attr_accessor :from, :to def change!(opts) self.from = opts.delete(:from) self.to = opts.delete(:to) self.text = opts.delete(:text) self.scope = opts.delete(:scope) self.steps << generic_from_to self.steps << unwrap_unnecessary_paragraphs self.steps << foster_orphaned_nodes run! self end private def change_this_node?(node) ( self.text ? node.text == self.text : true ) && ( self.scope ? node.parent.name == self.scope : true ) && ( node.name == self.from ) end def convert_inline_element_to_block? BLOCK_CONVERSION_ELEMENTS[:inlines].include?(self.from) && BLOCK_CONVERSION_ELEMENTS[:blocks].include?(self.to) end def generic_from_to return if convert_inline_element_to_block? Loofah::Scrubber.new do |node| node.name = self.to if change_this_node?(node) end end def unwrap_unnecessary_paragraphs Loofah::Scrubber.new do |node| node.replace(node.children.first) if unnecessary_paragraph?(node) end end def unnecessary_paragraph?(node) node.name == 'p' && node.children.size == 1 && Loofah::Elements::BLOCK_LEVEL.include?(node.children.first.name) end def foster_orphaned_nodes Loofah::Scrubber.new do |node| node.extend(FosterModule) node.foster! end end end module FosterModule def foster! if orphaned_li? self.replace wrap_li end end def orphaned_li? name == 'li' && parent.name !~ /ol|ul/ end def wrap_li Nokogiri.make("<ul>#{self}</ul>") end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
crazy_harry-0.2.1 | lib/crazy_harry/change.rb |
crazy_harry-0.2.0 | lib/crazy_harry/change.rb |
crazy_harry-0.1.2 | lib/crazy_harry/change.rb |