require 'facet/kernel/constant'
require 'nitro/helper/javascript'
module Nitro
# Generates client-side javascript code.
module ScriptCompiler
extend JavascriptHelper
def self.transform(text, compiler)
begin
client = constant("#{compiler.controller}::Client")
rescue Object
client = nil
end
if client
client.send :include, Nitro::ScriptGenerator
client = client.new
functions = {}
text.scan(/__nc_(.*)\(\)/) do |match|
functions[match.first] = true
end
script = ''
for fun in functions.keys
begin
client.buffer = ''
ret = client.send(fun.to_sym)
# the function code is accumulated in the client
# buffer.
function_code = client.buffer
# if the client action returs a String append it to
# the function code.
function_code << ret if ret.is_a?(String)
script << %{
function __nc_#{fun}() {
#{function_code}
}
}
rescue => ex
Logger.debug ex.inspect if $DBG
end
end
# Inject css in the head tag.
if css_buffer = compiler.shared[:css_buffer]
text.sub!(/<\/head>/) do |match|
%{
}
end
end
# Inject required javascript files in the head tag.
if required_files = compiler.shared[:js_required_files]
text.sub!(/<\/head>/) do |match|
%{
#{include_script *required_files.keys}
}
end
end
# Inject javascript just before the end of the
# template.
#--
# gmosx: injection happens at the end, so that the DOM
# tree is created. Dunno if this is valid xhtml though.
#++
js_buffer = compiler.shared[:js_buffer]
if script or js_buffer
text.sub!(/<\/body>/) do |match|
%{