Never been to DZone Snippets before?

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

About this user

Hendrik Mans http://www.mans.de

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Update selected attributes from a list

This transfers a list of selected attributes from a list (typically inside params[]) to an AR model object. More useful than attr_accessible, attr_protected et al.

   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

User model basics: age calculations

   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

User model basics: SHA256 passwords

   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
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS