Sha256: a1fd64a4b46123506ce6f6688d537de38ce248bff01fe331cab599a57fb7f7a0

Contents?: true

Size: 1.64 KB

Versions: 13

Compression:

Stored size: 1.64 KB

Contents

require 'active_model'
require 'active_record'
require 'active_support'

# :nodoc: namespace
module Authpwn

# :nodoc: namespace
module UserExtensions

# Augments the User model with an email virtual attribute.
module EmailField
  extend ActiveSupport::Concern

  included do
    validates_each :email do |record, attr, value|
      if record.email_credential
        unless record.email_credential.valid?
          record.email_credential.errors.each do |_, message|
            record.errors.add attr, message
          end
        end
      else
        record.errors.add attr, :blank
      end
    end
  end

  module ClassMethods
    # The user who has a certain e-mail, or nil if the e-mail is unclaimed.
    def with_email(email)
      credential = Credentials::Email.where(name: email).includes(:user).
          references(:user).first
      credential && credential.user
    end
  end

  # Credentials::Email instance associated with this user.
  def email_credential
    credentials.find { |c| c.instance_of?(Credentials::Email) }
  end

  # The e-mail from the user's Email credential.
  #
  # Returns nil if this user has no Email credential.
  def email
    credential = self.email_credential
    credential && credential.email
  end

  # Sets the e-mail on the user's Email credential.
  #
  # Creates a new Credentials::Email instance if necessary.
  def email=(new_email)
    if credential = self.email_credential
      credential.email = new_email
    else
      credentials << Credentials::Email.new(email: new_email)
    end
    new_email
  end
end  # module Authpwn::UserExtensions::EmailField

end  # module Authpwn::UserExtensions

end  # module Authpwn

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
authpwn_rails-0.23.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.22.1 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.22.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.21.1 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.21.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.20.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.19.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.18.2 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.18.1 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.18.0 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.17.2 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.17.1 lib/authpwn_rails/user_extensions/email_field.rb
authpwn_rails-0.17.0 lib/authpwn_rails/user_extensions/email_field.rb