【问题标题】:Rails-way - where to put this kind of helper method?Rails-way - 在哪里放置这种辅助方法?
【发布时间】:2023-05-24 07:00:01
【问题描述】:

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

这些“操作”中的每一个都有一个 URL,用户可以在其中完成操作,例如。如果缺少个人资料照片,他们可以上传该页面的 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 中,我将无法访问我的命名路由助手。如果我将它添加到我的用户模型中也是如此。

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

【问题讨论】:

  • 您应该可以在您的辅助方法中访问命名路由(以及任何其他视图辅助),但是您将无法在您的模型 UserCompleteness 中访问它们。

标签: ruby-on-rails


【解决方案1】:

这与 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 封装,这可能会使测试变得更加困难。如果您可以摆脱用户助手中的某些方法,而不是可能更好的类。

【讨论】:

    【解决方案2】:

    从我得到你的问题的那一点点来看,我认为你想要一种可以在控制器和视图中使用的方法。 在 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
    

    你可以在控制器和视图中使用方法current_user

    【讨论】:

    • 不是我的意思-对此感到抱歉:-)我的意思是在哪里放置需要使用命名路由的辅助方法。在我看来,我只需要这个。