【问题标题】:Access compute_asset_host from inside a rake task?从 rake 任务内部访问 compute_asset_host?
【发布时间】:2011-09-25 07:23:36
【问题描述】:

我尝试过包含 ActionView::Helpers::AssetTagHelper 和一堆它的变体,但我总是收到一条错误消息:NameError: undefined local variable or methodconfig' for main:Object`

更新了更多信息

我需要能够根据环境引用存储在不同服务器上的资源。在我的开发机器上,它将在 localhost:3000 上引用,在生产服务器上,它将在一个 CDN 地址上,而在暂存时,它将在另一个地址上。显然我们想先在本地测试这个 rake 任务,然后在 staging 上,最后在 staging 上,所以 rake 任务需要能够根据资产主机配置变量生成 URL。实际上,我甚至创建了一个名为 asset_path 的 ApplicationHelper 方法来在我的视图中执行此操作,但它基本上只是 compute_asset_host 的别名。但是,如果我在我的 rake 任务中包含 ApplicationHelper 并调用 asset_path,它会抱怨compute_public_path 未定义,然后如果我包含(或扩展)ActionView::Helpers::AssetTagHelper,它会从compute_asset_host 中抱怨undefined local variable or method 'config' for main:Object。所以我需要以某种方式调用任何实例化 ActionView::Helpers 使用的配置容器,以便 compute_asset_host 可以根据环境返回正确的 URL。

【问题讨论】:

  • 你能添加更多关于你想要完成的细节吗?我不清楚您为什么要在 rake 任务中调用 View 助手。

标签: ruby-on-rails-3 rake actionview


【解决方案1】:

这就是我的工作

task :it => :environment do
  include ActionView::Helpers
  include ApplicationHelper
  # your code here
end

【讨论】:

    【解决方案2】:

    这很丑陋,我试图绕过做这样的事情但是......

    namespace :test do
    
      def view(url_options = {}, *view_args)
        view_args[0] ||= ActionController::Base.view_paths
        view_args[1] ||= {}
    
        view = ActionView::Base.new(*view_args)
        routes = Rails::Application.routes
        routes.default_url_options = {:host => 'localhost'}.merge(url_options)
    
        view.class_eval do
          include ApplicationHelper
          include routes.url_helpers
        end
    
        assigns = instance_variables.inject(Hash.new) do |hash, name|
          hash.merge name[1..-1] => instance_variable_get(name)
        end
        view.assign assigns
    
        view
      end  
    
      task :it => :environment do
        param = ""
        puts ">>> compute_asset_host returns: [#{view.send("compute_asset_host", param)}]"
      end
    
    end
    

    ... 可能会让您朝着解决您遇到的问题的方向前进。

    PS:我在这里找到了查看方法:https://gist.github.com/592846

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2012-12-01
      • 2013-08-06
      • 2011-07-13
      • 1970-01-01
      相关资源
      最近更新 更多