2010-09-17 61 views
1

你能告訴我一種更好的方式來編寫代碼嗎?DRY功能更好的方法

使用從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 = data['locale'] 
    user.picture_url = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large' 
    user.fb_access_token = access_token 
    end 

回答

0

解決方案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 

解決方案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) 
2
hash['picture_url'] = something 
User.create(hash) 
0

的ActiveRecord的創建方法可以採取屬性的哈希值。由於您的散列鍵與訪問器方法完全匹配,因此您可以在設置數據['picture_url']之後以與之前相同的方式傳入User.create(散列)。塔斯社的答案基本上是正確的,但更精確地滿足你的代碼:

data['picture_url'] = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large' 
User.create(data) 
+0

如果我不-T都在關鍵的精確匹配價值和屬性? – 2010-09-17 17:28:00

+1

將非確切鍵的值分配給確切的鍵。 – Reactormonk 2010-09-18 11:53:46