如何在使用资产管道时为导轨中的功能开关创建“条件资产”?
问题描述:
我正在实施“功能开关”,以便管理员可以使用管理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'
是假的......
答
一个可能的解决方案可以创建两个体现,例如说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。在您的布局产量:ON_OFF并在视图中添加content_for:ON_OFF和测试@count到stylesheet_link_tag“on_off_switch”(更多细节rails documentation)
答
的解决方案似乎是刚刚上面放的条件在
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'
不过虽然在发展工作并没有在生产wortk和样式表将不包括在内。