encrypt.rb 2.2 KB

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