Rails-way - 在哪里放置这种辅助方法?

时间:2010-07-12 11:22:39

标签: ruby-on-rails

我正在努力寻找帮助方法的正确位置。该方法基本上“检查”用户模型对象,并且应该返回关于用户的“进展”的一些信息,例如。 “您需要添加图片”,“填写您的地址”或“添加您的电子邮件地址”。我正在检查的所有条件都不是必需的,它就像“这是你的个人资料完整性” - 在LinkedIn等上看到的功能。

这些“动作”中的每一个都有一个URL,用户可以在其中完成动作,例如。如果缺少个人资料照片,他们可以上传页面的网址。

因为我需要访问我的命名路由助手(例如new_user_image_path),所以我很难搞清楚Rails构造代码的方式。

我想用这样的DSL返回一个对象:

 class UserCompleteness
     def initialize(user)
     end

     def actions
        # Returns an array of actions to be completed
     end

     def percent
        # Returns a 'profile completeness' percentage
     end
 end

并使用以下内容进行操作:@completeness = user_completeness(current_user)

但是,如果我将其添加到我的application_helper中,则无法访问我的命名路由助手。如果我将它添加到我的用户模型中也是如此。

我应该在哪里放置这种辅助方法?

2 个答案:

答案 0 :(得分:0)

从小问题我得到了你的问题我想你想要一个可以在Controller和Views中使用的方法。 在application_controller.rb中完成这个简单的add方法,并将其命名为hepler_method

实施例: -

  class ApplicationController < ActionController::Base
    helper_method :current_user

    def current_user
      @current_user ||= User.find_by_id(session[:user])
    end

  end

您可以在Controller和视图中使用方法current_user

答案 1 :(得分:0)

这与Mailers的问题类似。它们是模型,不应跨越MVC边界,但需要生成视图。试试这个:

class UserCompleteness

  include ActionController::UrlWriter

  def initialize(user)
  end

  def actions
    # Returns an array of actions to be completed
    new_user_image_path(user)
  end

  def percent
    # Returns a 'profile completeness' percentage
  end
 end

但请注意,您正在破坏MVC封装,这可能会使测试更加困难。如果您可以在用户帮助程序中使用某些方法而不是可能更好的类。