【问题标题】:Is this a good DRY method in rails?这是rails中一个好的DRY方法吗?
【发布时间】:2013-11-05 00:13:18
【问题描述】:

我不想使用//= 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

所以我在辅助方法中使用了名为 yield 的名称,并且我有一个主要的 add_asset() 方法和两个特定于资产的方法。这是一个好方法吗?或者有没有更好的解决方案?

更新:

来自 rails 文档:

例如,如果你生成一个 ProjectsController,Rails 也会添加 app/assets/javascripts/projects.js.coffee 中的一个新文件,另一个位于 应用程序/资产/样式表/projects.css.scss。默认情况下,这些文件将 使用 require_tree 可以立即被您的应用程序使用 指示。有关更多详细信息,请参阅清单文件和指令 需要树。

您还可以选择包含特定于控制器的样式表和 JavaScript 文件仅在它们各自的控制器中使用 以下: 或 。确保您不是 但是使用 require_tree 指令,因为这将导致您的 资产被包含不止一次。

所以javascript_include_tagstylesheet_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]}")

【问题讨论】:

    标签: ruby-on-rails dry mixins yield assets


    【解决方案1】:

    我认为这是矫枉过正。

    如果你不喜欢 require full tr​​ee unordered,你可以手动一一要求。

    //= js_file_a
    //= js_file_b
    

    与您的解决方案比较:

    1. 您仍然需要自己输入文件名。

      def add_asset(*files)
      
    2. 当工作可以在其他地方轻松完成时,添加了几个不必要的助手。

    【讨论】:

    • 在控制器特定的 css 中?
    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 2012-08-21
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多