我不想用
//= require_tree .
(因为它加载了我所有的资产,我也不需要这些资产),并且不想每次都写
javasctipt_include_tag("my_controller")
。所以我决定做以下事情:
module ApplicationHelper
def add_asset(*files)
puts "DEBUG: add: " + files.to_s
content_for(:html_head) do
if GtFe::Application.assets.find_asset(*files)
yield :asset_include_tag
end
end
end
def javascript(*files)
add_asset(*files) do
content_for :asset_include_tag
javascript_include_tag(*files)
end
end
def stylesheet(*files)
add_asset(*files) do
content_for :asset_include_tag
stylesheet_link_tag(*files)
end
end
end
所以我在helper方法中使用名称命名的yield,并且我有一个
add_asset()
方法和两种特定于资产的方法。这样做是个好方法吗?或者有更好的解决方案吗?
更新:
从rails文档中:
例如,如果您生成ProjectsController,Rails也会添加
一个新文件位于app/assets/javascripts/projects.js.coffee,另一个位于
app/assets/stylesheets/projects.css.scss。默认情况下,这些文件将
使用requiretree立即准备好供应用程序使用
指令。有关详细信息,请参阅清单文件和指令
require_tree。
您也可以选择包含特定于控制器的样式表和
仅在其各自的控制器中使用
以下内容:<%=javascript_include_tag参数[:控制器]%>或<%=
stylesheet_link_tag参数[:控制器]%>。确保您没有
不过,使用requiretree指令,因为这将导致
资产被包含不止一次。
所以
javascript_include_tag
和
stylesheet_link_tag
是合理的。但这样做让员工干起来好吗?
更新2:
我得到了以下代码改进:
module ApplicationHelper
def add_asset(asset_type, *files)
puts "DEBUG: add #{asset_type} files: #{files}"
content_for(:html_head) do
files.each do |file|
puts "DEBUG: now add #{asset_type}: #{file}"
if GtFe::Application.assets.find_asset(file)
yield(:asset_include_tag, file)
end
end
end
end
def javascript(*files)
add_asset("js", *files) do
content_for :asset_include_tag
javascript_include_tag
end
end
def stylesheet(*files)
add_asset("css", *files) do
content_for :asset_include_tag
stylesheet_link_tag
end
end
end
然后我可以在每个视图/布局中写下:
= javascript(params[:controller], "#{params[:controller]}_#{params[:action]}")