我正在尝试找到一种从CoffeeScript文件自动生成Javascript的方法,就像你在Sinatra中很容易做到的那样:
require 'sinatra'
require 'coffee-script'
get '/*.js' do
name = params[:splat][0]
file_name = File.join("#{name}.coffee")
pass unless File.exists?(file_name)
content_type(:js, :charset => 'utf-8')
coffee(IO.read(file_name))
end这样,在我的代码中,即使我只得到了.js文件,我也可以表现得像存在.coffee文件一样。与使用客户端CoffeeScript编译器相比,它没有那么详细,错误也更少……
发布于 2012-07-04 16:40:04
谢谢leucos!
我也考虑过Rack中间件,但我想知道是否没有更"ramaze“的解决方案(比如innate)。
无论如何,这是有效的,它是伟大的!
以下是代码的修改版本:
require 'coffee-script'
# An attempt to allow Ramaze to generate Js file from coffee files
module Rack
class BrewedCoffee
def initialize(app, options = {})
@app = app
@lookup_path = options[:lookup_path].nil? ? [__DIR__] : options[:lookup_path]
end
def call(env)
name = env['PATH_INFO']
# Continue processing if requested file is not js
return @app.call(env) if File.extname(name) != '.js'
coffee_name = "#{name[0...-3]}.coffee"
@lookup_path.each do |p|
coffee_file = File.join(p, coffee_name)
next unless File.file?(coffee_file)
response_body = CoffeeScript.compile(File.read(coffee_file))
headers = {}
headers["Content-Type"] = 'application/javascript'
headers["Content-Length"] = response_body.length.to_s
return [200, headers, [response_body]]
end
@app.call(env)
end
end
end我清理了一些东西,并删除了Ramaze依赖,这样它就是一个纯粹的Rack中间件:)。
您可以使用它来调用:
m.use Rack::BrewedCoffee, :lookup_path => Ramaze.options.roots再见,安德烈亚斯
发布于 2012-07-04 15:26:44
处理这个问题的最好方法可能是编写您自己的机架中间件,并像下面这样使用它。您可能需要使用某种类型的缓存,这样就不会在每次调用时都从.coffee文件重新构建.js文件。
require 'ramaze'
class BrewedCoffee
def initialize(app)
@app = app
end
def call(env)
name = env['PATH_INFO']
# Continue processing if requested file is not js
return @app.call(env) if name !~ /\.js$/
# Caching & freshness checks here...
# ...
# Brewing coffee
name = name.split('.')[0..-2].join('.') + ".coffee"
Ramaze.options.roots.each do |p|
file_name = File.join("#{name}.coffee")
next unless File.exists?(file_name)
response_body = coffee(IO.read(file_name))
headers["Content-Type"] = 'application/javascript'
headers["Content-Length"] = response_body.length.to_s
[status, headers, response_body]
end
@app.call(env)
end
end
class MyController < Ramaze::Controller
map '/'
...
end
Ramaze.middleware! :dev do |m|
m.use(BrewedCoffee)
m.run(Ramaze::AppMap)
end
Ramaze.start这很快就被破解了,需要更多的爱,但你明白了。您可能不想在生产环境中这样做,而只是预先构建咖啡内容,否则会在sysops中遇到麻烦:D
https://stackoverflow.com/questions/11309738
复制相似问题