链轮中的条件要求

时间:2012-11-01 15:35:12

标签: ruby sprockets

如何使用Sprockets有条件地要求资产?

我在询问之前搜索了解决方案,并在Sprockets存储库中找到了这个讨论 - Conditional require

讨论的解决方案是使用ERB:

<% require_asset "#{ActiveScaffold.js_framework}/my_test" %>

我试过这种方式:

app.js.erb

<% if debug == true %>
   <% require_asset "lib-debug" %>
<% else %>
   <% require_asset "lib-min" %>
<%end%>

Rake文件

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

但是会导致以下错误:

  

#&lt;#:0x00000001576d30&gt;

的未定义局部变量或方法`debug'

肯定有一些易于修复的错误,但我是Ruby的新手并且无法发现它。

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是将以下内容添加到bundle_app方法中:

env.context_class.class_eval "def debug; #{!!debug}; end"

更新的bundle_app()方法:

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

答案 1 :(得分:1)

也许,因为您的示例使用debug作为参数,您可以使用结算在开发环境中拥有资产吗?

如果是,请在config / environments / development.rb

config.assets.precompile << 'lib-debug.js'
相关问题