Skip to content

Instantly share code, notes, and snippets.

@aablinov
Created May 13, 2020 16:58
Show Gist options
  • Save aablinov/ca61bf6ef809a4b402c4f54aa5b02e3d to your computer and use it in GitHub Desktop.
Save aablinov/ca61bf6ef809a4b402c4f54aa5b02e3d to your computer and use it in GitHub Desktop.
# gem https://github.com/AaronLasseigne/active_interaction
module Excursion
module Services
class NewUser < ActiveInteraction::Base
string :email
def execute
user = User.create(email: email)
if user.persisted?
user
else
errors.merge!(user.errors)
end
end
end
end
end
module Excursion
module Services
class JoinUser < ActiveInteraction::Base
object :record, class: Record
string :email
string :group
def execute
return unless can?
exists_user = User.find_by_email(email) # Or UserRepository.new.find(email) no matter
if exists_user
record.users << exists_user
else
user = NewUser.run!(email: email)
record.users << user
end
end
private
def can?
# some bussiness checks
errors.add('Business not valid')
false
end
end
end
end
# Before any form object you want to check email format etc. (grape/dry)
# Or create custom email type in ActiveInteraction and change string :email with email :email ¯\_(ツ)_/¯
params do
requires :email, regexp: /.+@.+/
end
service = Excursion::Services::JoinUser.run(record: Record.find, group: 'a', email: params[:email])
service.valid? ? service.result : service.errors.full_messages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment