我主要来自 C# 背景,目前正在学习 Ruby on Rails。浏览 railstutorial.org,我看到很多这样的代码(这个是代码 list 10.49):
class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update]
before_action :valid_user, only: [:edit, :update]
.
.
.
def edit
end
private
def get_user
@user = User.find_by(email: params[:email])
end
# Confirms a valid user.
def valid_user
unless (@user && @user.activated? &&
@user.authenticated?(:reset, params[:id]))
redirect_to root_url
end
end
end
现在,我学到的是让方法尽可能细化,方法名称尽可能提供信息。这里的方法 valid_user
检查用户是否有效,如果无效则重定向到 root_url
。
在这种情况下,我要做的是将方法重命名为 redirect_to_root_if_not_valid
,或者不使用单独的方法,而是使用类似 user.valid?
的方法如果我需要检查,然后在需要的地方重定向。
对我来说,方法名称和方法信息具有误导性,它不仅确认有效用户,如果用户无效,它还会重定向到某个地方。
这对我来说是不是很奇怪,因为我来自 C# 背景,还是这只是我不习惯的另一种做事方式?
最佳答案
您正在进入“做 x 的最佳方式是什么”的恐怖谷,而在 ruby 社区中,人们喜欢这样。不管怎样,我将就如何重构您的代码给出另一个意见:
创建一个authenticated?
和过滤方法[并将它们放在ApplicationController
中,您可能会重用它 |与否,这取决于逻辑是否可共享]。此外,我喜欢定义一个 user
方法和编写器,而不是使用过滤器来实现 [几乎] 相同的行为。
class ApplicationControlller < ActionController::Base
before_action :restrict_access_to_authenticated_users
private
def restrict_access_to_authenticated_users
redirect_to root_path unless authenticated?
end
def authenticated?(u = user)
u && u.activated? && u.authenticated?(:reset, params[:id])
end
attr_writer :user # I use this so you can overwrite the user without using the code beneath
def user
@user ||= User.find_by_email(params[:email])
end
end
关于ruby-on-rails - Ruby 中的方法定义和命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901330/