我正在使用 Ruby on Rails 3.2.2,我想知道以下代码具有或可能具有的优点/缺点:
class ApplicationController < ActionController::Base
before_filter :set_current_user_for_models
private
def set_current_user_for_models
User.current_user = User.find(...) # Find the user from cookies.
end
end
class User < ActiveRecord::Base
attr_accessible :current_user
private
def some_method(user)
if User.current_user == user
# Make a thing...
else
# Make another thing...
end
end
end
class Article < ActiveRecord::Base
def some_method(user)
if User.current_user == user
# Make a thing...
else
# Make another thing...
end
end
end
你有什么建议吗?您将如何改进代码?
在@tokland 对@Wawa Loo 答案的评论后更新
注意:主要区别在于User.current_user
应该在after_find
, after_create
,...
模型回调中更新。像这样的东西:
class User < ActiveRecord::Base
attr_accessible :current_user
after_initialize :some_method
private
def some_method
if User.current_user == self
# Make a thing...
else
# Make another thing...
end
end
end
class Article < ActiveRecord::Base
after_destroy :some_method
private
def some_method
if User.current_user == self.user
# Make a thing...
else
# Make another thing...
end
end
end