Sha256: 4bc248ebab7323d747730adf5b5228df802c2f1fcf685590b96bb862809514e3
Contents?: true
Size: 1.86 KB
Versions: 2
Compression:
Stored size: 1.86 KB
Contents
require 'singleton' require_relative '../../html_to_haml' require_relative '../../tools/html/attribute_handler' module HtmlToHaml::Html class AttributeConversionUseCase include Singleton HAML_TAG_LINES = "^\s*%(.*)$" MULTILINE_ERB_ATTRIBUTES_REGEX = /^\s*%.*[a-zA-Z1-9]+?=('|")[^'"]*\s*\n\s*=.*\n\s*[^'"]*("|')/ def convert_attributes(html:) erb_converted_html = remove_erb_newlines(html: html) erb_converted_html.gsub(/#{HAML_TAG_LINES}/) do |matched_elem| haml_with_replaced_attributes(haml: matched_elem) end end private def haml_with_replaced_attributes(haml:) attribute_handler = AttributeHandler.new haml_without_attributes = haml.gsub(/\s*([a-zA-Z1-9]+?)=('|").*?('|")/) do |matched_elem| # This could go into the AttributeHandler, but at the moment this is the only place # that is aware of the erb syntax and that makes the AttributeHandler more isolated. attr = escape_erb_attributes(attr: matched_elem) attribute_handler.add_attribute(attr: attr) '' end "#{haml_without_attributes}#{attribute_handler.attributes_string}" end def remove_erb_newlines(html:) # Erb attributes may be malformed to have their own line and a '=' in front # (if the html already went through the erb converter) # This changes them back into something that can be updated above html.gsub(MULTILINE_ERB_ATTRIBUTES_REGEX) do |erb_attr| erb_attr.gsub(/\n\s*(=|.*?'|.*?")/, ' \1') end end def escape_erb_attributes(attr:) attr.gsub(/=('|")(.*?)\s*=\s*([^\s]*)(\s*.*)('|")/, '=\1\2 #{\3}\4\5') # put erb text inside #{} globally .gsub(/('|")\s*#\{(.*)\}\s*('|")/, '\2') # Remove strings and #{} around simple erb expressions (with no non-erb) .gsub(/\s('|")$/, '\1') # Get rid of any extra whitespace. end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
html-to-haml-0.0.6 | lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb |
html-to-haml-0.0.5 | lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb |