#coding: utf-8 =begin * 20111115 find bug 避免每次重新生成CodeHash的对象 * TODO 在项目中要分自己用的还是提供给外边的 =end require 'fileutils' module GlobalConst SAMPLE_FILE = "templates/code_hashes/code_hash.yml.sample" APP_CODE_HASHES = "config/code_hashes/" mattr_accessor :global_data @@global_data = {} def self.method_missing(method_name, *args, &block) ms = method_name.to_sym return @@global_data[ms] if @@global_data.key?(ms) raise "Method name: #{method_name}(#{args.inspect}) is not defined!" end def self.load_code_hashes!(hash_or_file = SAMPLE_FILE) if hash_or_file.is_a?(Hash) h = hash_or_file else h = YAML.load(File.open(hash_or_file)) unless h.is_a?(Hash) #格式异常检查,过滤掉空和无效文件 puts "==>Warning: Invalid arguments: #{hash_or_file}, it does not evalute to a Hash!你自己去看看,别找我!" return end end nh = h.symbolize_keys nh.keys.each do |k| if @@global_data.key?(k) puts "==>Warning: new value(from #{hash_or_file.inspect}) is set for key:#{k}! Please check that is your need!" end @@global_data[k] = CodeHash.new(nh[k]) end end def self.load_app_code_hashes!(dir = APP_CODE_HASHES) if defined? Rails target = "#{Rails.root}/#{APP_CODE_HASHES}" if File.directory?(target) hfiles = Dir.glob("#{target}**/*.yml") hfiles.each do |f| load_code_hashes!(f) end end end end #为引用项目生成样例文件, TODO rake方式生成 def self.setup_sample(yml_file = "#{APP_CODE_HASHES}code_hash.yml.sample") if defined? Rails target = "#{Rails.root}/#{yml_file}" unless File.exists?(target) path = File.dirname(target) FileUtils.mkpath(path) #默认覆盖已有 FileUtils.cp(SAMPLE_FILE, target) end end end #将一个hash和array写入data下的yaml结构中 def self.yamlize(hash_or_array = {}, file_name = nil) return if hash_or_array.nil? hash = if hash_or_array.is_a?(Array) hash_or_array.inject({}) do |r, k| r[k] = nil r end else hash_or_array end method_key = file_name.nil? ? "hash" : file_name.to_s name = "#{method_key}_#{Time.now.to_i}" file = "#{Rails.root}/data/#{name}.yml" path = File.dirname(file) Fileutils.mkpath(path) unless File.directory?(path) File.open(file, 'w+') do |f| f.puts YAML.dump(method_key.to_sym=>hash) end end end