Here is the piece of my controller action that takes a session[:auth]
hash and then assigns the values to the ActiveRecord object represented by @user
whilst the key names happen to be the same.
def new
@user = User.new
if session[:auth].present?
@user.first_name = session[:auth].extra.raw_info.first_name
@user.last_name = session[:auth].extra.raw_info.last_name
@user.username = session[:auth].extra.raw_info.username
@user.email = session[:auth].extra.raw_info.email
end
end
I wonder if there's a way to eliminate the duplications in assigning the values from the hash to the object.
2 Answers 2
This should do
def new
attrs = %w(first_name last_name username email).map do |param|
[param, session[:auth].extra.raw_info.send(param)]
end
@user = User.new Hash[attrs]
end
To add something to Flambino's answer, I'd suggest moving any non-trivial code to the model (code is then easier to test, re-usable and controllers are kept simple):
class User
def self.new_from_auth(auth)
attributes = [:first_name, :last_name, :username, :email]
user_attributes = if auth
info = auth.extra.raw_info
Hash[attributes.map { |attr| [attr, info.send(attr)] }]
else
{}
end
User.new(user_attributes)
end
end
class UsersController
def new
@user = User.new_from_auth(session[:auth])
end
end