Skip to content

Instantly share code, notes, and snippets.

View thiagofm's full-sized avatar
🐢
Slowly coming back to OSS

Thiago Massa thiagofm

🐢
Slowly coming back to OSS
  • Berlin, Germany
View GitHub Profile
@thiagofm
thiagofm / include_vs_extend.rb
Last active October 18, 2022 19:20
Include vs Extend
module FlippedTable
def table
"┻━┻"
end
end
class AngryTableFlipper
# Including FlippedTable's methods...
# as instance methods
include FlippedTable
@thiagofm
thiagofm / include.rb
Created October 17, 2022 10:44
include ruby table flip
# Let's define a FlippedTable class
module FlippedTable
# Define method we want to use in different classes
def table
"┻━┻"
end
end
class AngryTableFlipper
# Include it to a class that will use it
@thiagofm
thiagofm / prepend.rb
Created October 13, 2022 10:21
prepend
class Wheel
def tire
puts "Tire is flat, needs service"
end
end
Wheel.new.tire
# Tire is flat, needs service
module SpareTire
@thiagofm
thiagofm / bang.rb
Created October 12, 2022 10:05
bang methods
# Bang method behavior: upcase!
email = "test@test.com"
# Upcasing a string, but not changing the variable email's value
email.upcase
# => "TEST@TEST.COM"
email
# => "test@test.com"
# Using bang to upcase a string
@thiagofm
thiagofm / avoiding_nils.rb
Created October 5, 2022 10:32
Avoiding nils in Ruby
# Using OpenStruct to mimic an object with the 'posts method'
user = OpenStruct.new(posts: [:post1, :post2])
# Using if user as a nil checker
user.posts if user
# => [:post1, :post2]
# Can be replaced with the safe navigation operator
user&.posts
# => [:post1, :post2]
# Ruby 3.1+
users = [
{ name: "Yukihiro Matsumoto", age: 57 },
{ name: "Kabosu the Shiba Inu", age: 16 },
{ name: "Thiago Massa", age: 33 }
]
def fetch_age_from_person(person, hash)
hash => [*, {name: ^person, age: age}, *]
@thiagofm
thiagofm / play_song.rb
Created September 16, 2022 10:25
play_song.rb
class PlaySong
def initialize(song)
@song = song
end
def call
# Here you implement your service object
"🎶 #{song}"
end
@thiagofm
thiagofm / pattern_matching_magic.rb
Created September 5, 2022 11:11
Pattern Matching Magic
# Creating a complex hash, with nested keys
my_complex_hash = {
users: [
{name: "Yukihiro Matsumoto", age: 57},
{name: "Kabosu the Shiba Inu", age: 16},
{name: "Thiago Massa", age: 33}
]
}
@thiagofm
thiagofm / pattern_matching_type.rb
Created September 4, 2022 08:43
Ruby Pattern Matching on Type
# Ruby pattern matching based on Type (=> operator)
[1,2,3] => [1, Integer, my_variable]
# This means:
# We want to assign `my_variable` (variable binding),
# but only if the first position is 1 and second position is an Integer)
my_variable # => 3 ✨
# What if it doesn't match? You get an exception 💣
[1,2,3] => [Integer, String, my_variable]
# [1, 2, 3]: String === 2 does not return true (NoMatchingPatternError)
@thiagofm
thiagofm / Procfile.dev
Last active August 27, 2022 14:53
Procfile.dev for debugging
web: rdbg -n --open=vscode -c -- bin/rails server -p 3000
js: yarn build --watch