我发现自己在写助手,以使我的观点非常清晰。但是,助手并不自然而然地成为类,而只是模块内部的一组方法。结果,这些方法不会像使用params进行初始化那样共享数据。因此,我最终多次传递数据。它很烦人。有没有办法在共享价值的课程中放一个课程?
这是我要弄干的一个例子-是的,它离最佳代码还很远,请只关注我要解决的问题;我不想浪费时间做一个完美的例子。在下面,传递了选项,但最终我将其传递给其他方法,等等。
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
%>
答案 0 :(得分:2)
没有什么可以阻止您自己开设一些课程,例如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 %>