Last active
January 10, 2020 14:45
-
-
Save thomasbrus/644915ba37f5134a20bc266f20c98e0e to your computer and use it in GitHub Desktop.
Pattern match example (Ruby 2.7)
This file contains 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 'pry' | |
class Category | |
def initialize(attributes) | |
@id, @name = *attributes.values_at(:id, :name) | |
end | |
def valid? | |
errors.empty? | |
end | |
def errors | |
messages = [] | |
messages << "id is missing" if @id.to_s.empty? | |
messages << "name is missing" if @name.to_s.empty? | |
messages | |
end | |
end | |
module CategoryMutator | |
def self.create(attributes) | |
category = Category.new(attributes) | |
category.valid? ? [:ok, category] : [:error, category.errors] | |
end | |
end | |
def example(category_attributes) | |
case CategoryMutator.create(category_attributes) | |
in :ok, result | |
puts "Created category #{result.inspect}" | |
in :error, reason | |
puts "Error: #{reason.inspect}" | |
end | |
end | |
example(id: 1, name: "Category 1") #=> Created category #<Category:0x00007fb7468b3d00 @id=1, @name="Category 1"> | |
example(id: 2, name: "") #=> Error: ["name is missing"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment