From 7226e478b58b8cf9540c548967e6625ee6a851b9 Mon Sep 17 00:00:00 2001 From: nex3 Date: Tue, 10 Apr 2007 00:29:57 +0000 Subject: [PATCH] Some progress made on html2haml understanding ERB. Loops remain a problem. git-svn-id: svn://hamptoncatlin.com/haml/trunk@491 7063305b-7217-0410-af8c-cdc13e5119b9 --- lib/haml/exec.rb | 8 +++++++- lib/haml/html.rb | 39 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/lib/haml/exec.rb b/lib/haml/exec.rb index f2867968..fd6cd1fc 100644 --- a/lib/haml/exec.rb +++ b/lib/haml/exec.rb @@ -225,6 +225,8 @@ END def initialize(args) super + @module_opts = {} + begin require 'haml/html' rescue LoadError => err @@ -243,6 +245,10 @@ Description: Transforms an HTML file into corresponding Haml code. Options: END + opts.on('-r', '--rhtml', 'Parse RHTML tags.') do + @module_opts[:rhtml] = true + end + super end @@ -252,7 +258,7 @@ END input = @options[:input] output = @options[:output] - output.write(::Haml::HTML.new(input).render) + output.write(::Haml::HTML.new(input, @module_opts).render) end end diff --git a/lib/haml/html.rb b/lib/haml/html.rb index a410d1a1..da388d12 100644 --- a/lib/haml/html.rb +++ b/lib/haml/html.rb @@ -3,6 +3,7 @@ require File.dirname(__FILE__) + '/../haml' require 'haml/engine' require 'rubygems' require 'hpricot' +require 'cgi' module Haml # This class contains the functionality used in the +html2haml+ utility, @@ -12,10 +13,20 @@ module Haml # Creates a new instance of Haml::HTML that will compile the given template, # which can either be a string containing HTML or an Hpricot node, # to a Haml string when +render+ is called. - def initialize(template) + def initialize(template, options = {}) + @@options = options + if template.is_a? Hpricot::Node @template = template else + if template.is_a? IO + template = template.read + end + + if @@options[:rhtml] + match_to_html(template, /<%=(.*?)-?%>/m, 'loud') + match_to_html(template, /<%(.*?)-?%>/m, 'silent') + end @template = Hpricot(template) end end @@ -56,6 +67,10 @@ module Haml end # :stopdoc: + + def self.options + @@options + end TEXT_REGEXP = /^(\s*).*$/ @@ -112,7 +127,11 @@ module Haml class ::Hpricot::Elem def to_haml(tabs = 0) - output = "#{tabulate(tabs)}" + output = "#{tabulate(tabs)}" + if HTML.options[:rhtml] && name[0...5] == 'haml:' + return output + HTML.send("haml_tag_#{name[5..-1]}", self.innerHTML) + end + output += "%#{name}" unless name == 'div' && (attributes.include?('id') || attributes.include?('class')) if attributes @@ -133,6 +152,22 @@ module Haml output end end + + def self.haml_tag_loud(text) + "= #{text.gsub(/\n\s*/, '; ').strip}\n" + end + + def self.haml_tag_silent(text) + text.split("\n").map { |line| "- #{line.strip}\n" }.join + end + + private + + def match_to_html(string, regex, tag) + string.gsub!(regex) do + "#{CGI.escapeHTML($1)}" + end + end # :startdoc: end end