【问题标题】:How can I create 'conditional assets' for feature switches in rails when using the asset pipeline?使用资产管道时,如何为 Rails 中的功能切换创建“条件资产”?
【发布时间】:2014-11-29 15:09:55
【问题描述】:

我正在实施“功能开关”,以便管理员可以使用管理员 Web 界面打开和关闭新功能。

我可以在诸如

之类的视图中轻松做到这一点
- if FeatureSwitch.where(name: 'display_demo_feature_switch_image', status: 'on').count > 0 
  # in reality would refactor that query to the controller/model. put here for clarity.
  %br
  %br
  %div{class: "onoffswitch"}
    %input{type: "checkbox", name: "onoffswitch", class: "onoffswitch-checkbox", id: "myonoffswitch"}
    %label{class: "onoffswitch-label", for: "myonoffswitch"}
      %span{class: "onoffswitch-inner"}
      %span{class: "onoffswitch-switch"}

但是,当我使用资产管道并使资产“有条件地”包含在内时,如何在视图中执行此操作?

所以,如果我有一个 css 资产清单 (app/assets/stylesheets/application.css):

/*
 *= require_self
 *= require main
 *= require default
 *= require on_off_switch
 *= require jquery-ui-1.8.22.custom.css
*/

我怎样才能使require on_off_switch“有条件”,这取决于来自的真/假返回

FeatureSwitch
  .where(name: 'display_demo_feature_switch_image', status: 'on').count > 0  

我尝试将 application.css 重命名为 application.css.erb 并使用

<% if 'abc' == 'def' %> # While developing/testing
 *= require on_off_switch
<% end %>

但是尽管'abc' == 'def' 是假的,但资产总是包含在内...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 conditional asset-pipeline assets


    【解决方案1】:

    解决方案似乎只是将条件放入

    app/views/layout/application.html.haml #  (I use haml instead of erb)
    

    = stylesheet_link_tag 'application'
    - if FeatureSwitch.where(name: 'display_demo_feature_switch_image', status: 'on').count > 0
      = stylesheet_link_tag 'on_off_switch'
    

    虽然这在开发中有效,但在生产中不起作用,样式表也不会包含在内。

    【讨论】:

      【解决方案2】:

      一种可能的解决方案是创建两个清单,例如 on.css 和 off.css

      在你的控制器中添加一个 before_filter:

      def my_before_filter_name
        @count = FeatureSwitch.where(name: 'display_demo_feature_switch_image', status: 'on').count
      end
      

      顺便说一句,避免在视图中使用活动记录。

      在您的布局中:

      - if @count > 0
        = stylesheet_link_tag 'on.css'
      - else
        = stylesheet_link_tag 'off.css'
      

      请注意,您可能需要测试@count 是否存在。

      如果此解决方案不是您的最佳选择,您可以使用 content_for。在您的布局中 yield :on_off 并在您的视图中添加 content_for :on_off 并测试 @count 到 stylesheet_link_tag 'on_off_switch' (rails documentation 中的更多详细信息)

      【讨论】:

        猜你喜欢
        • 2018-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多