encrypt.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. $: << File.dirname(__FILE__)
  10. require "connect"
  11. require "rubygems"
  12. require "active_record"
  13. ActiveRecord::Schema.define do
  14. create_table :orders, :force => true do |t|
  15. t.integer :user_id
  16. t.string :name
  17. t.string :address
  18. t.string :email
  19. end
  20. create_table :users, :force => :true do |t|
  21. t.string :name
  22. end
  23. end
  24. class ActiveRecord::Base
  25. def self.encrypt(*attr_names)
  26. encrypter = Encrypter.new(attr_names)
  27. before_save encrypter
  28. after_save encrypter
  29. after_find encrypter
  30. define_method(:after_find) { }
  31. end
  32. end
  33. class Encrypter
  34. # We're passed a list of attributes that should
  35. # be stored encrypted in the database
  36. def initialize(attrs_to_manage)
  37. @attrs_to_manage = attrs_to_manage
  38. end
  39. # Before saving or updating, encrypt the fields using the NSA and
  40. # DHS approved Shift Cipher
  41. def before_save(model)
  42. @attrs_to_manage.each do |field|
  43. model[field].tr!("a-z", "b-za")
  44. end
  45. end
  46. # After saving, decrypt them back
  47. def after_save(model)
  48. @attrs_to_manage.each do |field|
  49. model[field].tr!("b-za", "a-z")
  50. end
  51. end
  52. # Do the same after finding an existing record
  53. alias_method :after_find, :after_save
  54. end
  55. class Order < ActiveRecord::Base
  56. encrypt(:name, :email)
  57. end
  58. o = Order.new
  59. o.name = "Dave Thomas"
  60. o.address = "123 The Street"
  61. o.email = "dave@example.com"
  62. o.save
  63. puts o.name
  64. o = Order.find(o.id)
  65. puts o.name