From f204f4e8f14cde6e4d4c6aafc55251a8d488a78d Mon Sep 17 00:00:00 2001 From: Torsten Date: Sun, 18 Dec 2022 20:14:54 +0200 Subject: [PATCH] fix haml filter and update spec to include interpolation --- lib/ruby2js/haml.rb | 41 +++++++++++++++++++++++++++++++++++------ spec/haml_spec.rb | 38 +++++++++++++++++++++++++++++++------- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/lib/ruby2js/haml.rb b/lib/ruby2js/haml.rb index 4b414737..325f42d5 100644 --- a/lib/ruby2js/haml.rb +++ b/lib/ruby2js/haml.rb @@ -15,13 +15,42 @@ # (Note missing brackets: ruby syntax, js sematics) # require "haml" +require "haml/filters" +require "haml/filters/base" + +module Haml + class Filters + class Ruby2JS < Base + def compile(node) + temple = [:multi] + temple << [:static, ""] + temple + end + + #Copird from text base, added ruby2js convert + def compile_ruby!(temple, node) + text = node.value[:text] + if ::Haml::Util.contains_interpolation?(node.value[:text]) + # original: Haml::Filters#compile + text = ::Haml::Util.unescape_interpolation(text).gsub(/(\\+)n/) do |s| + escapes = $1.size + next s if escapes % 2 == 0 + "#{'\\' * (escapes - 1)}\n" + end + text.prepend("\n") + + temple << [:dynamic, "::Ruby2JS.convert(#{text} ).to_s"] + else + temple << [:static, ::Ruby2JS.convert(text).to_s] + end + end + -module Ruby2JS - module Haml::Ruby2JS - include Haml::Filters::Base - def render(text) - converted = Ruby2JS.convert(text).to_s - "" end end end + + +Haml::Filters.registered[:ruby2js] ||= Haml::Filters::Ruby2JS diff --git a/spec/haml_spec.rb b/spec/haml_spec.rb index 168cbad9..4a18469c 100644 --- a/spec/haml_spec.rb +++ b/spec/haml_spec.rb @@ -1,21 +1,45 @@ +gem 'minitest' +require 'minitest/autorun' +require 'ruby2js/filter/functions' + require 'haml' require 'ruby2js/haml' describe 'HAML filter' do it 'should convert ruby to javascript' do - template = %{ + haml = %{ :ruby2js alert 'Hello' } # unindent template so that the first line starts in column 1 - template.gsub!(/^#{template[/\A\s+/]}/, '') + # As in, it is valid haml + haml.gsub!(/^#{haml[/\A\s+/]}/, '') + + #copied from from haml tests, module RenderHelper - haml_engine = Haml::Engine.new(template) - output = _(haml_engine.render) + output = Haml::Template.new({}) { haml }.render(Object.new, {}) - output.must_include "' + _(output).must_include "' end + + it 'should convert ruby with interpolation to javascript' do + haml = %{ + :ruby2js + alert HASH{2 + 2} + } + + # unindent template so that the first line starts in column 1 + # As in, it is valid haml + haml.gsub!(/^#{haml[/\A\s+/]}/, '') + haml.gsub!("HASH", "#") #stop ruby interpreteting the 2 + 2 + + #copied from from haml tests, module RenderHelper + output = Haml::Template.new({}) { haml }.render(Object.new, {}) + + _(output).must_include 'alert(4)' + end + end