Skip to content

Instantly share code, notes, and snippets.

@serradura
Created July 13, 2021 15:39
Show Gist options
  • Save serradura/3046ae9a9a1df56689ae97bc898b4e04 to your computer and use it in GitHub Desktop.
Save serradura/3046ae9a9a1df56689ae97bc898b4e04 to your computer and use it in GitHub Desktop.
u-case - attribute validations
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'kind'
gem 'u-case'
gem 'activemodel'
gem 'pry'
end
Micro::Case.config do |config|
config.enable_activemodel_validation = true
end
Person = Struct.new(:name, :age)
class CreatePerson < Micro::Case
attribute :name, validates: {kind: String, presence: true}
attribute :age, validates: {kind: Integer, allow_nil: true}
def call!
Success result: {person: Person.new(name, age)}
end
end
class CreatePerson2 < Micro::Case
attribute :input, validates: {kind: Hash}
validate :input_properties_must_be_valid
def call!
name, age = input.values_at(:name, :age)
Success result: {person: Person.new(name, age)}
end
private
def input_properties_must_be_valid
return unless input.is_a?(Hash)
name = input[:name]
unless name.is_a?(String) && name.present?
errors.add(:input, 'name must be a filled string')
end
end
end
class PersonInputValidator < ActiveModel::Validator
def validate(object)
input = object.input
errors = object.errors
unless input.is_a?(Hash)
errors.add(:input, 'must be a Hash') and return
end
name = input[:name]
unless name.is_a?(String) && name.present?
errors.add(:input, 'name must be a filled string')
end
end
end
=begin
app/
models/
create_person/
input_validator.rb
create_person.rb
class CreatePerson < Micro::Case
require_relative "create_person/input_validator"
attribute :input
validates_with InputValidator
end
=end
class CreatePerson3 < Micro::Case
attribute :input
validates_with PersonInputValidator
def call!
name, age = input.values_at(:name, :age)
Success result: {person: Person.new(name, age)}
end
end
PersonInputKind = ->(input) do
return false unless input.is_a?(Hash)
name = input[:name]
name.is_a?(String) && name.present?
end
class CreatePerson4 < Micro::Case
attribute :input, validates: {kind: PersonInputKind}
def call!
name, age = input.values_at(:name, :age)
Success result: {person: Person.new(name, age)}
end
end
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment