有没有一种方法可以让Ruby在提供.js文件之前对其进行编辑

Is there a way to make Ruby edit .js files before they are served?

本文关键字:文件 js 编辑 一种 方法 Ruby 有没有      更新时间:2023-12-28

我想写一些东西(用Ruby),在将其提供给用户之前,它会自动将console.log()添加到我的javascript资产的每一行。这个工具将极大地帮助我调试大型js文件,节省时间并给我一个回溯。我知道rails有各种内置的助手。。。也许是发球前?我知道链轮在上菜前会把文件捣碎。。

以下是解决方案:

if Rails.env.development?
  Sprockets::Server.module_eval do
    alias_method :ok_response_orig, :ok_response
    def ok_response(asset, env)
      asset.instance_eval do
        #The next string to be appended
        @source += %{
        'n;(function(){
            console.log("Called from #{File.basename(@pathname)}");
          })();
          }
        @length = Rack::Utils.bytesize(@source)
        @digest = Digest::MD5.new.update(@source).hexdigest
      end if asset.instance_eval{@pathname.to_s}.include?(".js") #You might want to add .coffee here
      ok_response_orig(asset, env)
    end
    def etag_match?(*args)
      true
    end
  end
end

享受吧。附言:仅在开发环境中使用。