Access compute_asset_host from inside a rake task?
I've tried including ActionView::Helpers::AssetTagHelper and a bunch of variants of that, but I always get an error saying NameError: undefined local variable or method
config' for main:Object`
Updated with more info
I need to be able to reference a resource that is stored on different servers depending on the environment. On my development machine it will be referenced at localhost:3000, on the production server it will be at one CDN address, and on staging it will be at yet another. Obviously we want to test this rake task locally first, then on staging and then finally on staging so the rake tasks needs to be able to generate URLs based on the asset host configuration variable. I actually went so far as to create an ApplicationHelper method called asset_path
to do this in my views, but it's basically just an alias for compute_asset_host. However, if I include Applicati开发者_如何转开发onHelper in my rake task and call asset_path
it complains that compute_public_path is undefined, and then if I include (or extend) ActionView::Helpers::AssetTagHelper it complains about undefined local variable or method 'config' for main:Object
from inside compute_asset_host. So I need to somehow invoke whatever instantiates the config container that is used by ActionView::Helpers so that compute_asset_host can return the proper URL based on the environment.
It is ugly and I try to get around doing things like this but...
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
... may start you in a direction to solve the problem you are having.
PS: I found the view method here: https://gist.github.com/592846
This is what I do
task :it => :environment do
include ActionView::Helpers
include ApplicationHelper
# your code here
end
精彩评论