module Rid module Makros # inject makros, that is: # replace makro with content from libs # def inject_makros! inject_makro! "code" do |filename| value = libs.at(filename) raise "code makro injection failed!\nNo lib available for %s" % filename unless value value end inject_makro! "json" do |filename| value = libs.at(filename) raise "json makro injection failed!\nNo lib available for %s" % filename unless value expand_json_makro filename, value end end # reject makros, that is: # replace makro generated content with makro # def reject_makros! return if injections.empty? injections.reverse.each do |inj| makro, target, lib, start, size = inj["makro"], inj["target"], inj["lib"], inj["start"], inj["size"] value = hash.at(target) value[start, size] = "// !#{makro} #{lib}" end end private # provide access to lib hash # def libs hash["lib"] || {} end # provide access to injections array # def injections hash["injections"] || [] end # builds a javascript variable assignment line for filename with value # 'var %s = %s;' % [filename.split(/[\.\/]/).join('_'), value.to_json] def expand_json_makro(filename, value) name = filename.sub(/\..*$/, '') parts = name.split('/') if parts.size > 1 var = "var #{parts.first};" 0.upto(parts.size - 2) do |i| v = parts[0..i].join('.') var << " if (!#{v}) #{v} = {};" end var << "\n" var << "#{parts.join('.')} = %s;" else var = "var #{name} = %s;" end var % value.to_json end # injects a makro and yields block with the filenames for found makros # def inject_makro!(makro, &block) hash.flatten.each do |key, value| next unless value.is_a?(String) # do not try to inject makros in attachments, libs and injections array next if key =~ /^_attachments|libs|injections/ new_value = value.gsub(/\/\/\s*!#{makro}\s+[\S]+$/) do |match| start = Regexp.last_match.begin(0) filename = match.sub(/^.*!#{makro}\s*(\S+).*$/, '\1') value = block.call(filename) store_injection makro, key, filename, start, value.size value end self.hash.update_at key, new_value end end # Store injection values in injections array # def store_injection(makro, target, lib, start, size) hash["injections"] ||= [] hash["injections"] << { "makro" => makro, "target" => target, "lib" => lib, "start" => start, "size" => size } end end end