Last active
October 15, 2020 21:32
-
-
Save serradura/080a2ab9ee2518f265e00c2131b3fef0 to your computer and use it in GitHub Desktop.
"Immutable" objects (PORO VS u-attributes)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'u-attributes', '~> 2.6.0' | |
end | |
# ------------------- ------------------- | |
class Person | |
include Micro::Attributes.with(:initialize, :accept) | |
attribute :name, default: -> value { String(value).strip }, | |
reject: :empty?, | |
freeze: true | |
def greet | |
"Hi my name is #{name}!" if accepted_attributes? | |
end | |
end | |
# ------------------- ------------------- | |
person1 = Person.new(name: 'Rodrigo') | |
puts person1.greet | |
person2 = person1.with_attribute(:name, '') | |
puts person2.greet | |
person3 = person1.with_attribute(:name, 'Serradura') | |
puts person3.greet | |
p [person1, person2, person3].map(&:name) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person | |
attr_reader :name | |
def initialize(name: nil) | |
@errors = [] | |
@name = String(name).strip.freeze | |
@errors << 'name must be filled' if @name.empty? | |
end | |
def valid? | |
@errors.empty? | |
end | |
def greet | |
"Hi my name is #{name}!" if valid? | |
end | |
def with_name(value) | |
self.class.new(name: value) | |
end | |
end | |
# ------------------- ------------------- | |
person1 = Person.new(name: 'Rodrigo') | |
puts person1.greet | |
person2 = person1.with_name('') | |
puts person2.greet | |
person3 = person1.with_name('Serradura') | |
puts person3.greet | |
p [person1, person2, person3].map(&:name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment