2011-06-29 57 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