如何刷新Rails / Sprockets以在资产之后了解生产服务器上的新清单:预编译

问题描述 投票:2回答:3

我们有一个需要运行资产的用例:在部署/重启过程之外进行预编译,因此最好不必重新启动Rails服务器进程。这在乘客环境中是否可行?

我一直在试图在Rake任务中尝试一堆东西并摆弄Rails.application.config.assets的东西,但没有任何东西让应用程序拾取对摘要的更改,除了用/usr/bin/env touch ~/project/current/tmp/restart.txt重新启动Passenger

ruby-on-rails-3 rake passenger sprockets capistrano3
3个回答
1
投票

我们最终选择了2部分解决方案:

第1部分是设置应用程序以命中redis来存储'assets:version'(我们只是带有时间戳)。然后,只要我们的流程完成预编译,我们就会使用最新的时间戳更新此资产版本。

第2部分是我们在我们的主application_controller中添加了一个before_filter :check_assets_version,我们所有其他控制器都继承自。这个方法看起来像这样:

  def check_assets_version
    @@version ||= 1
    latest_version = get_assets_version # wrapped call to redis to get latest version
    # clear assets cache if current version isn't the same as the latest version from redis
    unless latest_version.blank? || latest_version.to_s == @@version
      @@version = latest_version
      if Rails.env.production? || Rails.env.sandbox? || Rails.env.experimental?
        nondev_reset_sprockets
      else
        dev_reset_sprockets @@version
      end
    end
  end

这两个重置方法如下所示:

  def nondev_reset_sprockets
    manifest = YAML.load(File.read(Rails.root.join("public","assets","manifest.yml")))
    manifest.each do |key, value|
      Rails.application.config.assets.digests[key] = value
    end
  end

nondev重置将每个值“填充”到新生成的清单文件的内存中

  def dev_reset_sprockets(version)
    environment = Rails.application.assets
    environment = environment.instance_variable_get('@environment') if environment.is_a?(Sprockets::Index)
    environment.version = version
  end

dev重置只是踢sprockets“版本”值,以便它认为(正确的)它需要重新分析并实时重新编译最新的资产。


1
投票

更新生产资产的另一种方法如下:

Rails.application.assets_manifest.instance_eval do
    new_manifest = Sprockets::Manifest.new(manifest.dir, manifest.filename)
    @data = new_manifest.instance_variable_get(:@data)
end

0
投票

对于Rails 4(Sprockets 2.11),您可以:

  Rails.application.assets_manifest = Sprockets::Manifest.new(Rails.env, Rails.application.assets_manifest.path)
  # see sprockets-rails/lib/railtie.rb
  ActionView::Base.assets_manifest = Rails.application.assets_manifest
© www.soinside.com 2019 - 2024. All rights reserved.