Skip to content

Instantly share code, notes, and snippets.

@MaryKuz
Created March 28, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaryKuz/584095c34f4eebc0ed74f93ca566cfc5 to your computer and use it in GitHub Desktop.
Save MaryKuz/584095c34f4eebc0ed74f93ca566cfc5 to your computer and use it in GitHub Desktop.
Start writing the Session class
class Session
include ActiveModel::Validations
attr_reader :email, :password, :user
def initialize params
params = params.try(:symbolize_keys) || {}
@user = params[:user]
@email = params[:email]
@password = params[:password]
end
validate do |model|
if user
model.errors.add :password, 'is invalid' unless user.authenticate password
else
model.errors.add :email, 'not found'
end
end
def save!
raise ActiveModel::StrictValidationFailed unless valid?
user.create_auth_token value: SecureRandom.uuid
end
def destroy!
user.auth_token.destroy!
end
def auth_token
user.try(:auth_token).try(:value)
end
def as_json *args
{ auth_token: auth_token }
end
def decorate
self
end
private
def user
@user ||= User.find_by email: email
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment