Created
March 28, 2019 12:09
-
-
Save MaryKuz/584095c34f4eebc0ed74f93ca566cfc5 to your computer and use it in GitHub Desktop.
Start writing the Session class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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