gpt4 book ai didi

ruby-on-rails-3 - 在 Rails 中,如何在使用 javascript_include_tag 之前检查 javascript 文件是否存在

转载 作者:行者123 更新时间:2023-12-03 00:49:54 24 4
gpt4 key购买 nike

在 Rails 3.2 应用程序中,我想在将 javascript_include_tag 包含在文件中之前检查 Assets 管道中是否存在 javascript 文件。像这样的东西:

<% if javascript_file_exists? %>
<%= javascript_include_tag "#{controller_name}_controller" %>
<% end %>

我想这样做,这样 JavaScript 文件的缺失就不会导致错误。有办法做到这一点吗?

最佳答案

更Rails 的方式是使用助手。这允许您检查文件的 Coffeescript 或 JavaScript 版本:

def javascript_exists?(script)
script = "#{Rails.root}/app/assets/javascripts/#{params[:controller]}.js"
File.exists?(script) || File.exists?("#{script}.coffee")
end

然后您可以在布局中使用它:

<%= javascript_include_tag params[:controller], :media => "all"  if javascript_exists?(params[:controller]) %>

您可以对 CSS 执行相同的操作:

 -- helper --
def stylesheet_exists?(stylesheet)
stylesheet = "#{Rails.root}/app/assets/stylesheets/#{params[:controller]}.css"
File.exists?(stylesheet) || File.exists?("#{stylesheet}.scss")
end

-- layout --
<%= stylesheet_link_tag params[:controller], :media => "all" if stylesheet_exists?(params[:controller]) %>


编辑:更新了#javascript_exists?

我最近对我的 javascript_exists? 帮助程序进行了一些更改:

def javascript_exists?(script)
script = "#{Rails.root}/app/assets/javascripts/#{script}.js"
extensions = %w(.coffee .erb .coffee.erb) + [""]
extensions.inject(false) do |truth, extension|
truth || File.exists?("#{script}#{extension}")
end
end

在应用程序布局中调用它:

<%= javascript_include_tag params[:controller]  if javascript_exists?(params[:controller]) %>

现在将处理更多扩展并使用注入(inject)来确定文件是否存在。然后,您可以根据应用程序的需要向扩展数组中添加更多扩展。


编辑 DEUX:更新了#stylesheet_exists?

相同,但对于样式表:

def stylesheet_exists?(stylesheet)
stylesheet = "#{Rails.root}/app/assets/stylesheets/#{stylesheet}.css"
extensions = %w(.scss .erb .scss.erb) + [""]
extensions.inject(false) do |truth, extension|
truth || File.exists?("#{stylesheet}#{extension}")
end
end


编辑最后(可能):干燥

def asset_exists?(subdirectory, filename)
File.exists?(File.join(Rails.root, 'app', 'assets', subdirectory, filename))
end

def image_exists?(image)
asset_exists?('images', image)
end

def javascript_exists?(script)
extensions = %w(.coffee .erb .coffee.erb) + [""]
extensions.inject(false) do |truth, extension|
truth || asset_exists?('javascripts', "#{script}.js#{extension}")
end
end

def stylesheet_exists?(stylesheet)
extensions = %w(.scss .erb .scss.erb) + [""]
extensions.inject(false) do |truth, extension|
truth || asset_exists?('stylesheets', "#{stylesheet}.css#{extension}")
end
end

关于ruby-on-rails-3 - 在 Rails 中,如何在使用 javascript_include_tag 之前检查 javascript 文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com