2
\$\begingroup\$

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.

asked May 27, 2014 at 8:37
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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
answered May 27, 2014 at 9:18
\$\endgroup\$
2
\$\begingroup\$

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
answered May 27, 2014 at 14:55
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.