Skip to content

Instantly share code, notes, and snippets.

@thomasbrus
Last active January 10, 2020 14:45
Show Gist options
  • Save thomasbrus/644915ba37f5134a20bc266f20c98e0e to your computer and use it in GitHub Desktop.
Save thomasbrus/644915ba37f5134a20bc266f20c98e0e to your computer and use it in GitHub Desktop.
Pattern match example (Ruby 2.7)
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