【问题标题】:Conditional require in SprocketsSprockets 中的条件要求
【发布时间】:2012-11-05 13:05:29
【问题描述】:

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

在询问之前我已经在 Google 上搜索了解决方案,并在 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%>

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

但是会导致如下错误:

# 的未定义局部变量或方法“调试”>

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

【问题讨论】:

    标签: ruby sprockets


    【解决方案1】:

    也许,由于您的示例使用 debug 作为参数,您可以使用sett 来在开发环境中拥有资产?

    如果是这样,在 config/environments/development.rb 中

    config.assets.precompile << 'lib-debug.js'
    

    【讨论】:

    • 谢谢,这很有趣!但是我更喜欢直接在 JS 代码中做出这样的决定,这样我的构建文件就不会知道应用程序的事务。
    【解决方案2】:

    一种可能的解决方案是将以下内容添加到 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 2017-07-11
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多