扩展File类
module Utils
class File
class << self
# 递归调用返回目录中的所有文件
def findfiles(dir, &block)
files = []
if ::File.exist?(dir)
if ::File.ftype(dir) == 'file'
files << dir
block.call(dir) if block
else
Dir.foreach(dir) do |entry|
unless [".", "..", "_svn", ".svn"].include?(entry)
files += findfiles("#{dir}/#{entry}", &block)
end
end
end
else
p "No such file or directory - #{dir}"
end
files
end
# 所有目录
def directories(dir, options={}, &block)
skip_dir = (options[:skip_dir]||[]) + [".", "..", "_svn", ".svn"]
Dir.entries(dir).collect do |item|
if ::File.ftype(::File.join(dir, item)) == 'directory' && !skip_dir.include?(item)
block.call(item) if block
item
end
end.compact
end
end
end
end
rake命令
require 'tempfile'
require 'yaml'
# 添加命名空间
namespace :dev do
#添加描述
# 在最终发布前,需要运行该命令,对javascript、css进行合并和压缩处理。
desc 'Compress javascript and stylesheets'
task :compress do
compress_of(:type=>'js')
compress_of(:type=>'css')
end
private
def compress_of(options)
build_path = "#{RAILS_ROOT}/lib/tasks/compressor"
command = "java -jar #{build_path}/yuicompressor-2.4.2.jar --charset utf8"
type = options[:type] || 'js'
work_path = "#{RAILS_ROOT}/public/#{type == 'js' ? 'javascripts' : 'stylesheets'}"
temp = Tempfile.new('compress')
files = get_files_from_config(type == 'js' ? 'javascripts' : 'stylesheets', 'development')
File.open(temp.path, 'a') do |f|
files.each do |file|
f.puts File.open(file, 'r') { |js| js.read }
puts "merge #{file}"
end
end
output_file = "#{work_path}/#{options[:output] || "all.#{type}"}"
system("#{command} --type #{type} -o #{output_file} #{temp.path}")
puts "build one compress file to #{output_file}"
puts ''
end
# 从config.yml配置文件中读取文件列表
def get_files_from_config(type, name = RAILS_ENV)
configuration_file = "#{RAILS_ROOT}/public/#{type}/config.yml"
config = YAML::load(ERB.new(IO.read(configuration_file)).result)
env_config = config[name]||{}
exclude_config = config['exclude']||{} #有些文件可能需要排除
work_path = "#{RAILS_ROOT}/public"
files = []
(env_config['items']-(exclude_config['items']||[])).each do |item|
tmp_files = []
Utils::File.findfiles("#{work_path}/#{type}/#{item}") do |file|
tmp_files << file #.sub(work_path, '')
end
files += tmp_files.sort
end
files
end
end
config.yml 格式
development: &development
items:
- jquery-ui-1.7.2.custom.css #jquery默认的uicss
- jquery-ui-1.7.2.pack.css #修改jquery默认的uicss
# 注意,为了加快产品执行效率,其实在产品模式下并不会用该配置,在此仅作为示例
# 直接在页面中硬编码为safore.js
# 请参见: D:\App\www\eb\trunk\app\views\layouts\a\_meta.rhtml
production:
items:
- all.css