Skip to content

Commit

Permalink
Merge pull request #33 from B-CDD/examples-service-objects
Browse files Browse the repository at this point in the history
Add examples/service_objects
  • Loading branch information
serradura authored Feb 20, 2024
2 parents 1ba99a3 + 066abd9 commit cbe44b4
Show file tree
Hide file tree
Showing 13 changed files with 433 additions and 0 deletions.
74 changes: 74 additions & 0 deletions examples/service_objects/Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# frozen_string_literal: true

if RUBY_VERSION <= '3.1'
puts 'This example requires Ruby 3.1 or higher.'
exit! 1
end

task default: %i[bcdd_result_transitions]

task :config do
require_relative 'config'
end

desc 'creates an account and an owner user through BCDD::Result'
task bcdd_result_transitions: %i[config] do
result = nil

bench = Benchmark.measure do
result = Account::OwnerCreation.call(
owner: {
name: "\tJohn Doe \n",
email: ' [email protected]',
password: '123123123',
password_confirmation: '123123123'
}
)
end

p result

puts "\nBenchmark: #{bench}"
end

desc 'creates an account and an owner user directly through ActiveRecord'
task raw_active_record: %i[config] do
require_relative 'config'

result = nil

bench = Benchmark.measure do
email = '[email protected]'

ActiveRecord::Base.transaction do
User.exists?(email:) and raise "User with email #{email} already exists"

user = User.create!(
uuid: ::SecureRandom.uuid,
name: 'John Doe',
email:,
password: '123123123',
password_confirmation: '123123123'
)

executed_at = ::Time.current

user.token.nil? or raise "User with email #{email} already has a token"

user.create_token!(
access_token: ::SecureRandom.hex(24),
refresh_token: ::SecureRandom.hex(24),
access_token_expires_at: executed_at + 15.days,
refresh_token_expires_at: executed_at + 30.days
)

account = Account.create!(uuid: ::SecureRandom.uuid)

Account::Member.create!(account: account, user: user, role: :owner)

result = { account: account, user: user }
end
end

puts "\nBenchmark: #{bench}"
end
11 changes: 11 additions & 0 deletions examples/service_objects/app/models/account.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true

class Account < ActiveRecord::Base
has_many :memberships, inverse_of: :account, dependent: :destroy, class_name: '::Account::Member'
has_many :users, through: :memberships, inverse_of: :accounts

where_ownership = -> { where(account_members: {role: :owner}) }

has_one :ownership, where_ownership, dependent: nil, inverse_of: :account, class_name: '::Account::Member'
has_one :owner, through: :ownership, source: :user
end
10 changes: 10 additions & 0 deletions examples/service_objects/app/models/account/member.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# frozen_string_literal: true

class Account::Member < ActiveRecord::Base
self.table_name = 'account_members'

enum role: { owner: 0, admin: 1, contributor: 2 }

belongs_to :user, inverse_of: :memberships
belongs_to :account, inverse_of: :memberships
end
15 changes: 15 additions & 0 deletions examples/service_objects/app/models/user.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

class User < ActiveRecord::Base
has_secure_password

has_many :memberships, inverse_of: :user, dependent: :destroy, class_name: '::Account::Member'
has_many :accounts, through: :memberships, inverse_of: :users

where_ownership = -> { where(account_members: { role: :owner }) }

has_one :ownership, where_ownership, inverse_of: :user, class_name: '::Account::Member'
has_one :account, through: :ownership, inverse_of: :owner

has_one :token, inverse_of: :user, dependent: :destroy, class_name: '::User::Token'
end
7 changes: 7 additions & 0 deletions examples/service_objects/app/models/user/token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true

class User::Token < ActiveRecord::Base
self.table_name = 'user_tokens'

belongs_to :user, inverse_of: :token
end
47 changes: 47 additions & 0 deletions examples/service_objects/app/services/account/owner_creation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# frozen_string_literal: true

class Account
class OwnerCreation < ApplicationService
input do
attribute :uuid, :string, default: -> { ::SecureRandom.uuid }
attribute :owner

before_validation do |input|
input.uuid = input.uuid.strip.downcase
end

validates :uuid, presence: true, format: { with: /\A[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\z/i }
validates :owner, presence: true, type: ::Hash
end

def call(attributes)
rollback_on_failure {
Given(attributes)
.and_then(:create_owner)
.and_then(:create_account)
.and_then(:link_owner_to_account)
}.and_expose(:account_owner_created, %i[user account])
end

private

def create_owner(owner:, **)
::User::Creation.call(owner).handle do |on|
on.success { |output| Continue(user: { record: output[:user], token: output[:token] }) }
on.failure { |output| Failure(:invalid_owner, **output) }
end
end

def create_account(uuid:, **)
account = ::Account.create(uuid:)

account.persisted? ? Continue(account:) : Failure(:invalid_record, **account.errors.messages)
end

def link_owner_to_account(account:, user:, **)
Member.create!(account:, user: user.fetch(:record), role: :owner)

Continue()
end
end
end
79 changes: 79 additions & 0 deletions examples/service_objects/app/services/application_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# frozen_string_literal: true

class ApplicationService
Error = ::Class.new(::StandardError)

class Input
def self.inherited(subclass)
subclass.include ::ActiveModel::API
subclass.include ::ActiveModel::Attributes
subclass.include ::ActiveModel::Dirty
subclass.include ::ActiveModel::Validations::Callbacks
end
end

class << self
def input=(klass)
const_defined?(:Input, false) and raise ArgumentError, 'Attributes class already defined'

unless klass.is_a?(::Class) && klass < (ApplicationService::Input)
raise ArgumentError, 'must be a ApplicationService::Attributes subclass'
end

const_set(:Input, klass)
end

def input(&block)
return const_get(:Input, false) if const_defined?(:Input, false)

klass = ::Class.new(ApplicationService::Input)
klass.class_eval(&block)

self.input = klass
end

def inherited(subclass)
subclass.include ::BCDD::Result::Context.mixin(config: { addon: { continue: true } })
end

def call(arg)
new(input.new(arg)).call!
end
end

private_class_method :new

attr_reader :input

def initialize(input)
@input = input
end

def call!
::BCDD::Result.transitions(name: self.class.name) do
if input.invalid?
Failure(:invalid_input, **input.errors.messages)
else
call(input.attributes.deep_symbolize_keys)
end
end
end

def call(attributes)
raise Error, 'must be implemented in a subclass'
end

private

def rollback_on_failure(model: ::ActiveRecord::Base)
result = nil

model.transaction do
result = yield

raise ::ActiveRecord::Rollback if result.failure?
end

result
end
end
56 changes: 56 additions & 0 deletions examples/service_objects/app/services/user/creation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# frozen_string_literal: true

class User
class Creation < ApplicationService
input do
attribute :uuid, :string, default: -> { ::SecureRandom.uuid }
attribute :name, :string
attribute :email, :string
attribute :password, :string
attribute :password_confirmation, :string

before_validation do |input|
input.uuid = input.uuid.strip.downcase
input.name = input.name.strip.gsub(/\s+/, ' ')
input.email = input.email.strip.downcase
end

validates :uuid, presence: true, format: { with: /\A[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\z/i }
validates :name, presence: true
validates :email, presence: true, format: { with: ::URI::MailTo::EMAIL_REGEXP }
validates :password, :password_confirmation, presence: true
end

def call(attributes)
Given(attributes)
.and_then(:validate_email_uniqueness)
.then { |result|
rollback_on_failure {
result
.and_then(:create_user)
.and_then(:create_user_token)
}
}
.and_expose(:user_created, %i[user token])
end

private

def validate_email_uniqueness(email:, **)
::User.exists?(email:) ? Failure(:email_already_taken) : Continue()
end

def create_user(uuid:, name:, email:, password:, password_confirmation:)
user = ::User.create(uuid:, name:, email:, password:, password_confirmation:)

user.persisted? ? Continue(user:) : Failure(:invalid_record, **user.errors.messages)
end

def create_user_token(user:, **)
Token::Creation.call(user: user).handle do |on|
on.success { |output| Continue(token: output[:token]) }
on.failure { raise 'Token creation failed' }
end
end
end
end
37 changes: 37 additions & 0 deletions examples/service_objects/app/services/user/token/creation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# frozen_string_literal: true

class User::Token
class Creation < ApplicationService
input do
attribute :user
attribute :executed_at, :time, default: -> { ::Time.current }

validates :user, presence: true, type: ::User
validates :executed_at, presence: true
end

def call(attributes)
Given(attributes)
.and_then(:validate_token_existence)
.and_then(:create_token)
.and_expose(:token_created, %i[token])
end

private

def validate_token_existence(user:, **)
user.token.nil? ? Continue() : Failure(:token_already_exists)
end

def create_token(user:, executed_at:, **)
token = user.create_token(
access_token: ::SecureRandom.hex(24),
refresh_token: ::SecureRandom.hex(24),
access_token_expires_at: executed_at + 15.days,
refresh_token_expires_at: executed_at + 30.days
)

token.persisted? ? Continue(token:) : Failure(:token_creation_failed, **token.errors.messages)
end
end
end
20 changes: 20 additions & 0 deletions examples/service_objects/config.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# frozen_string_literal: true

require 'bundler/inline'

$LOAD_PATH.unshift(__dir__)

require_relative 'config/boot'
require_relative 'config/initializers/bcdd'

require 'db/setup'

require 'app/models/account'
require 'app/models/account/member'
require 'app/models/user'
require 'app/models/user/token'

require 'app/services/application_service'
require 'app/services/account/owner_creation'
require 'app/services/user/token/creation'
require 'app/services/user/creation'
17 changes: 17 additions & 0 deletions examples/service_objects/config/boot.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

require 'bundler/inline'

$LOAD_PATH.unshift(__dir__)

gemfile do
source 'https://rubygems.org'

gem 'sqlite3', '~> 1.7'
gem 'bcrypt', '~> 3.1.20'
gem 'activerecord', '~> 7.1', '>= 7.1.3', require: 'active_record'
gem 'type_validator'
gem 'bcdd-result', path: '../../'
end

require 'active_support/all'
11 changes: 11 additions & 0 deletions examples/service_objects/config/initializers/bcdd.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true

BCDD::Result.config.then do |config|
config.addon.enable!(:continue)

config.constant_alias.enable!('BCDD::Context')

config.pattern_matching.disable!(:nil_as_valid_value_checking)

# config.feature.disable!(:expectations) if Rails.env.production?
end
Loading

0 comments on commit cbe44b4

Please sign in to comment.