class HtmlToHaml::Html::DefaultConversionUseCase

Constants

CLOSING_HTML_REGEX
DOCTYPE_REGEX
ERB_LINE_REGEX
HAML_SYMBOL_REGEX
SELF_CLOSING_HTML_REGEX

For self-closing html tags that aren't self-closing by default

SELF_CLOSING_TAGS

Public Class Methods

new(html, remove_whitespace: true) click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 17
def initialize(html, remove_whitespace: true)
  # Since Haml uses whitespace in a way html doesn't, this starts by stripping
  # whitespace to start the next gsub with a clean slate. Unless the caller opts
  # out.
  @html = if remove_whitespace
            remove_html_whitespace(html: html)
          else
            html
          end
end

Public Instance Methods

convert() click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 28
def convert
  indentation_tracker = IndentationTracker.new(indentation_amount: HtmlToHaml::INDENTATION_AMOUNT)
  haml = @html.gsub(/#{DOCTYPE_REGEX}|#{ERB_LINE_REGEX}|#{CLOSING_HTML_REGEX}|#{SELF_CLOSING_HTML_REGEX}|#{self_closing_tag_regex}|#{HAML_SYMBOL_REGEX}|<|>|\n/) do |matched_elem|
    adjust_indentation_level(html: matched_elem, indentation_tracker: indentation_tracker)
    start_of_line = "\n#{indentation_tracker.indentation}"
    case matched_elem
      when /#{DOCTYPE_REGEX}/
        "#{matched_elem}\n"
      when /#{ERB_LINE_REGEX}/
        "#{start_of_line}#{matched_elem[1..-1]}"
      when /#{self_closing_tag_regex}/
        "#{start_of_line}%#{matched_elem[1..-1]}"
      when /#{HAML_SYMBOL_REGEX}/
        "#{start_of_line}#{matched_elem[1..-1].insert(-2, "\\")}"
      when "<"
        "#{start_of_line}%"
      else
        start_of_line
    end
  end
  remove_haml_whitespace(haml: haml)
end
self_closing_tag_regex() click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 51
def self_closing_tag_regex
  "<#{SELF_CLOSING_TAGS.join('|<')}\\s"
end

Private Instance Methods

adjust_indentation_level(html:, indentation_tracker:) click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 57
def adjust_indentation_level(html:, indentation_tracker:)
  case html
    when /#{CLOSING_HTML_REGEX}/
      indentation_tracker.close_html_tag
    when /#{self_closing_tag_regex}/
      indentation_tracker.start_self_closing_tag
    when ">", /#{HAML_SYMBOL_REGEX}/
      indentation_tracker.start_html_tag
  end
end
remove_haml_whitespace(haml:) click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 72
def remove_haml_whitespace(haml:)
  haml.lstrip.gsub(/(\n\s*)\n\s*%/, '\1%').gsub(/\n\s*\n/, "\n")
end
remove_html_whitespace(html:) click to toggle source
# File lib/html_to_haml/use_cases/html/default_conversion_use_case.rb, line 68
def remove_html_whitespace(html:)
  html.gsub(/^\s*/, "").delete("\n")
end