将助手方法返回值设置为实例变量

时间:2013-10-16 00:48:18

标签: ruby-on-rails ruby ruby-on-rails-4

所以我在面包屑中有一个应用程序范围的帮助方法,我在布局中使用所有视图页面。

以下是

的方法
- 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

1 个答案:

答案 0 :(得分:2)

助手是视图中包含的模块。它们不是通过实例变量访问的。

您应该能够直接在视图中访问助手中定义的方法。所以而不是写

- @BreadcrumbsHelper = breadcrumbs
- i = 0
- @BreadcrumbsHelper.each do |name, breadcrumb|
你会写一些像

这样的东西
- breadcrumbs.each do |name, breadcrumb|

您可能还想在循环之前捕获面包屑的数量,例如

- my_breadcrumbs = breadcrumbs
- breadcrumbs_count = my_breadcrumbs.size
- my_breadcrumbs.each do |name, breadcrumb|

并替换

@BreadcrumbsHelper.count

breadcrumbs_count