Skip to content

Instantly share code, notes, and snippets.

@aablinov
Created May 13, 2020 16:58
Show Gist options
  • Select an option

  • Save aablinov/ca61bf6ef809a4b402c4f54aa5b02e3d to your computer and use it in GitHub Desktop.

Select an option

Save aablinov/ca61bf6ef809a4b402c4f54aa5b02e3d to your computer and use it in GitHub Desktop.

Revisions

  1. aablinov created this gist May 13, 2020.
    57 changes: 57 additions & 0 deletions service.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    # 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