I am using Ruby on Rails 3.2.2 and I would like to know what advantages / disadvantages the following code has or could have:
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
Have you some advice? How would you improve the code?
Updated after the @tokland comment on the @Wawa Loo answer
Note: the main difference is that User.current_user should be updated also in after_find, after_create, ... model callbacks. Something like this:
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
Your code looks fine. I recommend you to read through this rails style guide for an overview on Rails development.