Conditional require in Sprockets

眉间皱痕 提交于 2019-12-06 08:53:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!