InstanceVariableAssumption:UsersController 为实例变量“@user”假设了太多
InstanceVariableAssumption: UsersController assumes too much for instance variable '@user'
我正在学习 Michael Hartl 教程 Rails 课程。在 chapter 7 上,我 运行 Reek on UsersController 并收到以下警告:
app/controllers/users_controller.rb -- 1 warning:
1:InstanceVariableAssumption: UsersController assumes too much for
instance variable '@user'
[https://github.com/troessner/reek/blob/master/docs/Instance-Variable-Assumption.md]
这是我的代码:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new user_params
if @user.save
flash[:success] = t "welcome_to_app"
redirect_to @user
else
render "new"
end
end
def show
@user = User.find_by id: params[:id]
return if @user
flash[:danger] = t "not_exist_user"
redirect_to root_path
end
private
def user_params
params.require(:user).permit :name, :email, :password,
:password_confirmation
end
end
请解释为什么我会收到此错误 InstanceVariableAssumption 以及如何解决此问题。
这看起来像是 reek recommends disabling on the GitHub page. According to this bug report 在项目中提交的气味之一,看来这只是由于 rails 制作了 reek 不喜欢的 use/encouraging 模式默认。
实例变量假设说:
Classes should not assume that instance variables are set or present outside of the current class definition.
好吧,这就是 约定优于配置 Rails 的用武之地。 Rails 有自己的做事方式,class: UsersController
依赖于 class: User
.
变量:@user
是UsersController
中定义的实例变量,但这是classUser
的对象。 Rails就是这样,你会发现它无处不在。
只是假设根据 Reek gem,这并不完美,但这是 Ruby 在 Rails 上的做法。
我们可以这样使用:
attr_reader :user, :users
那么所有的@user,@users都可以写成user
或者users
.
我正在学习 Michael Hartl 教程 Rails 课程。在 chapter 7 上,我 运行 Reek on UsersController 并收到以下警告:
app/controllers/users_controller.rb -- 1 warning:
1:InstanceVariableAssumption: UsersController assumes too much for instance variable '@user' [https://github.com/troessner/reek/blob/master/docs/Instance-Variable-Assumption.md]
这是我的代码:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new user_params
if @user.save
flash[:success] = t "welcome_to_app"
redirect_to @user
else
render "new"
end
end
def show
@user = User.find_by id: params[:id]
return if @user
flash[:danger] = t "not_exist_user"
redirect_to root_path
end
private
def user_params
params.require(:user).permit :name, :email, :password,
:password_confirmation
end
end
请解释为什么我会收到此错误 InstanceVariableAssumption 以及如何解决此问题。
这看起来像是 reek recommends disabling on the GitHub page. According to this bug report 在项目中提交的气味之一,看来这只是由于 rails 制作了 reek 不喜欢的 use/encouraging 模式默认。
实例变量假设说:
Classes should not assume that instance variables are set or present outside of the current class definition.
好吧,这就是 约定优于配置 Rails 的用武之地。 Rails 有自己的做事方式,class: UsersController
依赖于 class: User
.
变量:@user
是UsersController
中定义的实例变量,但这是classUser
的对象。 Rails就是这样,你会发现它无处不在。
只是假设根据 Reek gem,这并不完美,但这是 Ruby 在 Rails 上的做法。
我们可以这样使用:
attr_reader :user, :users
那么所有的@user,@users都可以写成user
或者users
.