2011-06-29 27 views
1

我试过,包括::的ActionView ::助手和AssetTagHelper一堆的变体,但我总是得到一个错误说NameError: undefined local variable or method配置”主:Object`从rake任务中访问compute_asset_host?

更多信息更新

我需要能够引用根据环境存储在不同服务器上的资源。在我的开发机器上,它将在localhost:3000上引用,在生产服务器上它将位于一个CDN地址,并且将在另一个CDN地址上启动。很明显,我们首先要在本地测试这个rake任务,然后进行分段测试,然后再进行分段测试,因此rake任务需要能够根据资产主机配置变量生成URL。我实际上甚至创建了一个名为asset_path的ApplicationHelper方法来在我的视图中执行此操作,但它基本上只是compute_asset_host的别名。但是,如果我将ApplicationHelper包含在我的rake任务中并调用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。

+0

您可以添加更多的细节,以你试图完成什么?我不清楚为什么你想在Rake任务中调用View助手。 – Midwire

+0

用更多信息更新了OP –

回答

0

这是丑陋的,我要尽量避开做这样的事情,但...

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

0

这是我做的

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