class HtmlToHaml::Html::AttributeConversionUseCase

Constants

HAML_TAG_LINES
MULTILINE_ERB_ATTRIBUTES_REGEX

Public Instance Methods

convert_attributes(html:) click to toggle source
# File lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb, line 12
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 Instance Methods

escape_erb_attributes(attr:) click to toggle source
# File lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb, line 42
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
haml_with_replaced_attributes(haml:) click to toggle source
# File lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb, line 21
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
remove_erb_newlines(html:) click to toggle source
# File lib/html_to_haml/use_cases/html/attribute_conversion_use_case.rb, line 33
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