Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/securely_hashed_attributes.rb

Overview

Adds the singleton method securely_hashes to ActiveRecord::Base

Class Method Summary collapse

Class Method Details

.securely_hashes(attrib, opts = {}) ⇒ Object

Adds a secure hash serialization to a column with the help of bcrypt. By default, attrib will serve as both the attribute to serialize and the name of the column that will hold the serialized value. If you want to serialize the value to a different column, use the :to option. Hashing of the value assigned to attrib will not occur until the model is persisted.

Examples:

class User < ActiveRecord::Base
  securely_hashes :password, :to => :password_hash
  securely_hashes :security_answer
end

new_user = User.new
new_user.password = 'my password'
new_user.security_answer = 'I am a turtle'
new_user.save
new_user.reload
new_user.password_hash                         # => '$2a$10blahetcetc...'
new_user.security_answer                       # => '$2a$10yaddayadda...'
new_user.password_hash   == 'not my password'  # => false
new_user.password_hash   == 'my password'      # => true
new_user.security_answer == 'I am a duck'      # => false
new_user.security_answer == 'I am a turtle'    # => true

Parameters:

  • attrib (#to_sym)

    attribute to serialize

  • opts (Hash) (defaults to: {})

    additional options

Options Hash (opts):

  • :to (#to_sym)

    The column to serialize attrib to. If this option is specified, a reader attribute will be created for attrib and a <attrib>= method will be create that copies the assigned value to the specified column.

  • :with (#to_sym) — default: BCryptPasswordColumn

    The coder to use to serialize and deserialize values assigned to attrib.

See Also:



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/securely_hashed_attributes.rb', line 55

def securely_hashes attrib, opts={}
  opts = SecurelyHashedAttributes::DEFAULT_ATTRIBUTE_OPTIONS.merge opts
  attrib = attrib.to_sym
  if opts[:to]
    col = opts[:to].to_sym
    serialize col, opts[:with]

    attr_reader attrib      
    define_method :"#{attrib}=" do |val|
      instance_variable_set(:"@#{attrib}", val)
      self[col] = val
    end
  else
    serialize attrib, opts[:with]
  end
end