Update selected attributes from a list
1 2 class ActiveRecord::Base 3 def transfer_attributes(source, *keys) 4 keys.each do |key| 5 self.send("#{key}=", source[key]) 6 end 7 end 8 end
DZone Snippets > hmans > activerecord
12875 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Hendrik Mans http://www.mans.de
1 2 class ActiveRecord::Base 3 def transfer_attributes(source, *keys) 4 keys.each do |key| 5 self.send("#{key}=", source[key]) 6 end 7 end 8 end
1 2 class User < ActiveRecord::Base 3 # ... 4 5 def age 6 (Time.now.year - birthday.year) - (turned_older? ? 0 : 1) rescue 0 7 end 8 9 def next_birthday 10 birthday.to_time.change(:year => (turned_older? ? 1.year.from_now : Time.now).year) 11 end 12 13 def turned_older? 14 (birthday.to_time.change(:year => Time.now.year) <= Time.now) 15 end 16 end
1 2 class User < ActiveRecord::Base 3 # ... 4 5 def password ; @password ; end 6 def password=(value) 7 self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp 8 self.password_sha = self.encrypt_password(value) 9 @password = value 10 end 11 12 def encrypt_password(cleartext) 13 Digest::SHA256.hexdigest(cleartext + self.password_salt) 14 end 15 16 def self.authenticate(nickname, password) 17 user = self.find_active_by_nickname(nickname) 18 raise "Username or Password invalid" if user.blank? || user.encrypt_password(password) != user.password_sha 19 return user 20 end 21 end