所以我有一个应用程序范围的面包屑辅助方法,我在布局中使用,在所有视图页面中。
这是下面的方法
- if request.fullpath != '/'
.row
.col-md-12
#breadcrumbs
= link_to 'home', '/'
%span »
- @BreadcrumbsHelper = breadcrumbs
- i = 0
- @BreadcrumbsHelper.each do |name, breadcrumb|
= link_to name, breadcrumb
- if i != (@BreadcrumbsHelper.count - 1)
%span »
- i = i + 1
据我了解,视图中的变量应该是实例变量而不是方法,但是在视图中声明实例变量似乎并没有什么意义,但我不知道该怎么做,是否可以接受只是将其保留为方法调用breadcrumbs.each do
,例如?那还能用吗?什么是最佳实践。
编辑(助手,以防万一):
module BreadcrumbsHelper
def breadcrumbs
current_path = request.fullpath
noparam_path = current_path.split('?')
path_parts = noparam_path[0].split('/')
path_parts.shift
counter = path_parts.size
new_paths = Hash.new
counter.times do
new_path = ""
path_name = ""
i = 0
path_parts.each do |part|
if i < counter
if new_path == ""
new_path = '/' + part
else
new_path = new_path + '/' + part
end
path_name = part
i = i + 1
end
end
counter = counter -1
#path functions
def routeValid(new_path)
route = "/" + new_path.gsub("_","/")
route_valid = true
begin
Rails.application.routes.recognize_path(route, :method => :get)
rescue
# error means that your route is not valid, so do something to remember that here
route_valid = false
end
return route_valid
end
def processPath(new_path, path_name, new_paths)
if routeValid(new_path) == true
#Optional Overrides
if path_name == "signup"
path_name = "sign up"
end
new_paths[path_name] = new_path
end
end
processPath(new_path, path_name, new_paths)
end
new_paths = Hash[new_paths.to_a.reverse]
return new_paths
end
end