问题
How can I conditionally require assets using Sprockets?
I've googled for solutions before asking and found this discussion in the Sprockets repository - Conditional require
The solution discussed there is to use ERB:
<% require_asset "#{ActiveScaffold.js_framework}/my_test" %>
I've tried it this way:
app.js.erb
<% if debug == true %>
<% require_asset "lib-debug" %>
<% else %>
<% require_asset "lib-min" %>
<%end%>
Rakefile
def bundle_app(debug)
env = Sprockets::Environment.new
env.append_path "app/"
env.js_compressor = Uglifier.new
assets = env.find_asset("app.js.erb")
return assets.to_s
end
But it results in the following error:
undefined local variable or method `debug' for #<#:0x00000001576d30>
Definitely there is some easy-to-fix error, but I'm new to Ruby and just can't spot it.
回答1:
Perhaps, since your example uses debug as a parameter, you could use settle for having the asset in the development environment?
If so, in config/environments/development.rb
config.assets.precompile << 'lib-debug.js'
回答2:
A possible solution is to add the following into the bundle_app method:
env.context_class.class_eval "def debug; #{!!debug}; end"
The updated bundle_app() method:
def bundle_app(debug)
env = Sprockets::Environment.new
env.append_path "app/"
env.context_class.class_eval "def debug; #{!!debug}; end"
env.js_compressor = Uglifier.new
assets = env.find_asset("app.js.erb")
return assets.to_s
end
来源:https://stackoverflow.com/questions/13180417/conditional-require-in-sprockets