Skip to content

Instantly share code, notes, and snippets.

@serradura
Created September 23, 2020 00:22
Show Gist options
  • Save serradura/ab448ec14717e41a408edc56fb12d8da to your computer and use it in GitHub Desktop.
Save serradura/ab448ec14717e41a408edc56fb12d8da to your computer and use it in GitHub Desktop.
Value and form objects using the u-attributes gem
require 'bundler/inline'
require 'digest'
gemfile do
source 'https://rubygems.org'
gem 'u-attributes', '~> 2.6.0'
end
class Password
include Micro::Attributes.with(:initialize)
attribute :value, default: -> value { String(value).strip },
protected: true
def ==(password)
self.value == Kind.of(self.class, password).value
end
def digest
@digest ||= Digest::SHA256.hexdigest(value)
end
end
Password.new('123456') == Password.new('123456') # true
Password.new('123456') == Password.new('123457') # false
require 'bundler/inline'
require 'digest'
gemfile do
source 'https://rubygems.org'
gem 'u-attributes', '~> 2.6.0'
end
class SignUpParams
include Micro::Attributes.with(:initialize, accept: :strict)
TrimString = -> value { String(value).strip }
attribute :email, default: TrimString, accept: -> str { str =~ /\A.+@.+\..+\z/ }
attributes :password, :password_confirmation, default: TrimString, reject: :empty?, private: true
def password_digest
Digest::SHA256.hexdigest(password) if password == password_confirmation
end
end
SignUpParams.new(email: nil, password: '', password_confirmation: "\n\r")
# ArgumentError (One or more attributes were rejected. Errors:)
# * "email" is invalid
# * "password" expected to not be empty?
# * "password_confirmation" expected to not be empty?
SignUpParams.new(email: '[email protected]', password: '123456', password_confirmation: '123456').password_digest
# "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment