Guest User

Untitled

a guest
Mar 17th, 2018
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. # Single responsibility
  2. # Creates a DB connection
  3. class UserRegistration
  4. EMAIL_REGEXP = /some regexp/
  5.  
  6. def initialize
  7. @connection = Database.new(username: 'root', password: '123', database: 'my_app')
  8. end
  9.  
  10. def perform(params)
  11. validate(params)
  12. register_user(params[:email], password[:password])
  13. send_welcome_email(params)
  14. end
  15.  
  16. private
  17.  
  18. def validate(params)
  19. email = params[:email]
  20. password = params[:password]
  21.  
  22. unless REGEXP.match(email)
  23. raise ValidationError.new('Invalid email')
  24. end
  25.  
  26. rows = @connection.fetch('SELECT * FROM users WHERE email = :email LIMIT 1', email: email)
  27.  
  28. if rows.length == 1
  29. raise ValidationError.new('Email taken')
  30. end
  31.  
  32. unless password.length > 6
  33. raise ValidationError.new('Invalid password')
  34. end
  35. end
  36.  
  37. def register_user(username, password)
  38. @connection.execute(
  39. 'INSERT INTO users name, password VALUES (:name, :password)',
  40. name: name,
  41. password: password
  42. )
  43. end
  44.  
  45. def send_welcome_email(params)
  46. smtp = Smtp.new('username:password@some_server')
  47. contents = File.contents('app/templates/welcome_email.html')
  48. contents = Template.new(contents).replace_vars(parmas)
  49. smtp.send(params[:email], body: body)
  50. end
  51. end
  52.  
  53.  
  54. registration = UserRegistration.new
  55. registration.perform(email: 'foo@bar.com', password: '1235abcd')
Add Comment
Please, Sign In to add comment