/app/forms/gobierto_admin/user_form.rb

https://github.com/PopulateTools/gobierto · Ruby · 74 lines · 53 code · 19 blank · 2 comment · 7 complexity · 4eff4f612129e5461cd109366b448ef1 MD5 · raw file

  1. # frozen_string_literal: true
  2. module GobiertoAdmin
  3. class UserForm < BaseForm
  4. attr_accessor(
  5. :id,
  6. :name,
  7. :bio,
  8. :email
  9. )
  10. delegate :persisted?, to: :user
  11. validates :user, :name, presence: true
  12. validates :email, format: { with: User::EMAIL_ADDRESS_REGEXP }
  13. def save
  14. return false unless valid?
  15. if save_user
  16. send_confirmation_instructions if email_changed?
  17. user
  18. end
  19. end
  20. def user
  21. @user ||= User.find_by(id: id).presence || build_user
  22. end
  23. private
  24. def build_user
  25. User.new
  26. end
  27. def email_changed?
  28. @email_changed
  29. end
  30. def save_user
  31. @user = user.tap do |user_attributes|
  32. user_attributes.name = name if name
  33. user_attributes.bio = bio if bio
  34. user_attributes.email = email if email
  35. end
  36. # Check changes
  37. @email_changed = @user.email_changed?
  38. if @user.valid?
  39. @user.save
  40. @user
  41. else
  42. promote_errors(@user.errors)
  43. false
  44. end
  45. end
  46. def send_confirmation_instructions
  47. user.regenerate_confirmation_token
  48. deliver_confirmation_email
  49. end
  50. protected
  51. def deliver_confirmation_email
  52. ::User::UserMailer.confirmation_instructions(user, user.site).deliver_later
  53. end
  54. end
  55. end