Skip to content

Instantly share code, notes, and snippets.

@serradura
Last active November 10, 2020 17:20
Show Gist options
  • Save serradura/30dc252e2d679a1daf5e112c5ea43238 to your computer and use it in GitHub Desktop.
Save serradura/30dc252e2d679a1daf5e112c5ea43238 to your computer and use it in GitHub Desktop.
u-case samples
require 'pp'
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'pry-byebug'
gem 'awesome_print'
gem 'activesupport', require: 'active_support/all'
gem 'activemodel'
gem 'u-case', '~> 4.2.1', require: 'u-case/with_activemodel_validation'
end
class CreateUser1 < Micro::Case
attributes :name, :email
def call!
normalize_attributes
.then(apply(:validate_attributes))
.then(apply(:create_record))
end
private
def normalize_attributes
Success result: {
name: String(name).capitalize,
email: String(email).strip.downcase
}
end
def validate_attributes(name:, email:, **)
return Success() if name.present? && email.include?('@')
Failure()
end
def create_record(name:, email:, **)
Success result: {
user: "user was created (name: #{name}, email: #{email})"
}
end
end
class CreateUser2 < Micro::Case
attribute :name, default: -> value { String(value).capitalize }
attribute :email, default: -> value { String(value).strip.downcase }
def call!
validate_attributes
.then(apply(:create_record))
end
private
def validate_attributes
return Success() if name.present? && email.include?('@')
Failure()
end
def create_record
Success result: {
user: "user was created (name: #{name}, email: #{email})"
}
end
end
class CreateUser3 < Micro::Case
attribute :name, {
default: -> value { String(value).capitalize },
validates: { presence: true }
}
attribute :email, {
default: -> value { String(value).strip.downcase },
validates: { format: { with: /@/ } }
}
def call!
Success result: {
user: "user was created (name: #{name}, email: #{email})"
}
end
end
result1 = CreateUser1.call(name: 'ricardo', email: ' [email protected] ')
result2 = CreateUser2.call(name: 'ricardo', email: ' [email protected] ')
result3 = CreateUser3.call(name: 'ricardo', email: ' [email protected] ')
pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment