Skip to content

Instantly share code, notes, and snippets.

@joeletizia
Last active August 18, 2016 15:24
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 joeletizia/8fe7766d26564a8f87a19e976aeadbb4 to your computer and use it in GitHub Desktop.
Save joeletizia/8fe7766d26564a8f87a19e976aeadbb4 to your computer and use it in GitHub Desktop.
defmodule EmailValidation do
def validate(email) do
email_validation_result = {:ok, email}
check_for_validity(email_validation_result)
|> check_if_email_taken
end
defp check_for_validity({:ok, email}) do
case check_against_regex(email) do
:ok -> {:ok, email}
:error -> {:error, :invalid_address}
end
end
defp check_if_email_taken({:error, reason}), do: {:error, reason}
defp check_if_email_taken({:ok, email}) do
query_the_db_blah_blah
end
end
module EmailValidation
module_function
def validate(email_string) # joe@harrys.com
email_validation_structure = ValidationStructure.new(status: :ok, value: email_string)
step_result = check_for_validity(email_validation_structure)
check_if_email_already_taken(step_result)
end
def check_for_validity(validation_structure)
return validation_strucutre if validation_strucutre.error?
if regex_matches_email(validation_strucutre, value)
validation_structure
else
ValidationStructure.new(status: :error, reason: :invalid_email)
end
end
private_module_function :check_for_validity
def check_if_email_already_taken(validation_structure)
return validation_strucutre if validation_strucutre.error?
if email_exists?(validation_structure.value)
ValidationStructure.new(status: :error, reason: :email_already_taken)
else
validation_structure
end
end
private_module_function :check_if_email_already_taken
end
# THIS FILE ALREADY EXISTS
class ValidationResult
def initialize(success: false, error_message: nil, value: value)
@success = success
@error_message = error_message
@value = value
end
def success?
!!success
end
def error?
!success?
end
attr_reader :error_message, :value
private
attr_reader :success
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment