DRY function in a better way
could you tell me a way to write this code in a better way ?
Create an user with data attributes fetched from facebook .
User.create do |user|
user.email = data['email']
user.password = Devise.friendly_token
user.facebook_uid = data['facebook_uid']
user.first_name = data['first_name']
user.last_name = data['last_name']
user.gender = data['gender']
user.timezone = data['timezone']
user.birthday = data['birthday']
user.link = data['link']
user.locale = da开发者_运维百科ta['locale']
user.picture_url = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large'
user.fb_access_token = access_token
end
hash['picture_url'] = something
User.create(hash)
Solution 1
User.create do |user|
data.each do |k, v|
user.send("#{k}=", v) if User.columns_hash.has_key?(k)
end
user.fb_access_token = access_token
user.password = Devise.friendly_token
user.picture_url = "https://graph.facebook.com/%s/picture?type=large" %
data['facebook_uid']
end
Solution 2
hash = {}
data.each do |k, v|
hash[k]= v if User.columns_hash.has_key?(k)
end
hash['fb_access_token'] = access_token
hash['password'] = Devise.friendly_token
hash['picture_url'] = "https://graph.facebook.com/%s/picture?type=large" %
data['facebook_uid']
User.create(hash)
ActiveRecord's create method can take a hash of attributes. Since your hash keys match the accessor methods exactly, you can just pass in User.create(hash) after setting data['picture_url'] the same way you did before. Tass's answer is essentially correct, but to more precisely match your code:
data['picture_url'] = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large'
User.create(data)
精彩评论