【问题标题】:Rails helpers as a classRails 助手作为一个类
【发布时间】:2019-08-21 18:01:29
【问题描述】:

我发现自己正在编写帮助程序以使我的观点非常清晰;然而,助手并不自然地以类的形式出现,而只是模块内的一组方法。因此,这些方法不会像使用参数调用 initialized 那样共享数据。所以我最终会多次传递数据。这很烦人。有没有办法把它放在一个共享值的类中?

这是一个我试图干掉的例子——是的,它远非最佳代码,请专注于我试图解决的问题;我不想浪费时间做一个完美的例子。在下面,正在传递选项,但我最终将它们传递给其他方法等。

module Dashboard::DashboardHelper
    def menu_item(link_ref, options={})
        title           = options.fetch(:title,     "")
        details         = options.fetch(:details,   "")
        highlight       = options.fetch(:highlight,     false)
        icon            = options.fetch(:icon,      "")
        first           = options.fetch(:first,     false)
        subs            = options.fetch(:subs, [])
        link_item_class = (first) ? "m-t-30" : " "

        content_tag(:li, 
                    menu_link_label(link_ref,title,details,icon,highlight), 
                    class: link_item_class
        )
    end

    def menu_link_label(link_ref, title, details, icon, highlight)
        link_to(menu_labels(title,details), link_ref, class: "detailed") +
        icon_thumbnail(icon,highlight)
    end

    def menu_labels(title, details)
        content_tag(:span, title, class: "title") +
        content_tag(:span, details, class: "details")       
    end

    def icon_thumbnail(name, family, highlight=true)
        classes = (highlight) ? "bg-success icon-thumbnail" : "icon-thumbnail"
        content_tag(:span,icon(name, family), class: classes)
    end

    def icon(name)
        (name.present?) ? content_tag(:i, nil, class:"fas fa-#{name}") : ""
    end
end

编辑:

选项哈希直接来自视图,通常采用以下形式:

<%= menu_item dashboard_root_path, 
    title: "Dashboard", 
    details: "12 New Updates", 
    icon: "fe:home",
    first: true,
    highlight: true
%>

【问题讨论】:

  • options hash 中的所有数据都来自一个模型吗?
  • 是一个直接来自view的hash,我在上面加个例子

标签: ruby-on-rails class helper


【解决方案1】:

没有什么能阻止你自己上一些课程,例如app/view_helpers 并在您的视图中使用它们

# app/view_helpers/menu.rb
class Menu
  attr_accessor :options
  def initialize(options={})
    # do something with your options
    # self.options[:header] = options.fetch(:header, '')
  end

  def header
    # use your options here
    content_tag(:h1, options[:header])
  end
end


# some_controller.rb
def index
  @menu = Menu.new
end


# index.html.erb
<%= @menu.header %>

【讨论】:

  • 谢谢。不知道为什么我把它复杂化了:)
猜你喜欢
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 2011-03-15
相关资源
最近更新 更多