module Xmvc module Generator class EnvironmentError < Xmvc::Error; status_code(11) ; end class Base TEMPLATE_PATH = "#{File.dirname(__FILE__)}/templates" def initialize *args @gsubs ||= {} @gsubs['namespace'] = Xmvc.environment['namespace'] end protected def ensure_directories_present! *args args.each do |a| Dir.mkdir(a) unless File.exists?(a) end end def ensure_no_overwrite! *args args.each do |a| if File.exists?(a) && !ARGV.include?("--force") raise Xmvc::FileExists.new("File already exists: #{a}") end end end def template(template_filename, destination_filename) #write the file File.open(destination_filename, 'w') {|f| f.puts(render_template(template_filename))} Xmvc.ui.confirm(" Created #{destination_filename}") end def render_template(template_filename, gsubs = @gsubs) #grab the template file text template_text = IO.read("#{TEMPLATE_PATH}/#{template_filename}") #translate the template file text gsubs.each_pair do |key, value| template_text.gsub!(Regexp.new("<%= @#{key} %>"), value) end template_text end def include_script html_filename, script_filename, dom_id end private ## # write a newly generated controller, model or view to environment.json # Unfortunately, we cannot JSON.parse the entire config/environment.json, since it contains comments # and such. Have to RegExp, pick-out the requested key, and JSON.parse the returned chunk. # Is this Regexp satisfactory?? Could probably be made better. # def to_environment(key, item) re = Regexp.new("\"#{key}\"\s*\:\s*(\\[.*?\\](?!\}))", Regexp::MULTILINE) content = File.read('config/environment.json') m = content.match(re) if m begin items = JSON.parse("#{m[1].strip}") rescue StandardError => e raise EnvironmentError.new("A JSON parsing error occured parsing config/environment.json. Failed to add #{key} to environment.json.") end if item.kind_of?(Hash) # <-- it's a view view = items.find {|i| i[item[:package]] } if view view[item[:package]] << item[:filename] else items << { item[:package] => [item[:filename]]} end else items << item unless items.include?(item) end File.open('config/environment.json', "w") do |file| file << content.gsub(re, "\"#{key}\": #{items.to_json}") end end end end end end