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 NameError => ex
client = nil
end
if client
client.send :include, Nitro::ScriptGenerator
client = client.new
functions = {}
params = {}
text.scan(/__nc_(.*)\((.*)\)/) do |match|
functions[match.first] = true
params[match.last] = 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 returns a String append it to
# the function code.
function_code << ret if ret.is_a?(String)
script << %{
function __nc_#{fun}(params) {
#{function_code}
}
}
rescue Object => ex
Logger.debug ex.inspect if $DBG
end
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.
required_files = Javascript.required_files
if crf = compiler.shared[:js_required_files]
required_files.concat(crf.keys)
end
unless required_files.empty?
text.sub!(/<\/head>/) do |match|
%{
#{include_script *required_files}
}
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|
%{