Module: AutoHash::ClassMethods

Defined in:
lib/auto_hash.rb

Instance Method Summary collapse

Instance Method Details

#auto_hash(*args) ⇒ Object

This is the macro style class method called from the AR model



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/auto_hash.rb', line 13

def auto_hash(*args)

  # Create a setter and "comparer" for each arg
  args.each do |field_name|

    # Dynamically define a new setter
    define_method "#{field_name}=" do |value|

      value = BCrypt::Password.create(value)

      # write_attribute() is the documented way to write to a AR
      # field after you've overridden the setter,
      # http://ar.rubyonrails.org/classes/ActiveRecord/Base.html
      write_attribute(field_name, value)

    end

    # Dynamically define the "comparer"
    define_method "#{field_name}" do

      BCrypt::Password.new(read_attribute(field_name))

    end

  end

end