Skip to content

Instantly share code, notes, and snippets.

View louishuyng's full-sized avatar

Louis Nguyen louishuyng

View GitHub Profile
@louishuyng
louishuyng / handle_timeout_error.ruby
Created June 20, 2023 04:29
Handling timeout error
require 'timeout'
begin
status = Timeout::timeout(5) {
# Something that should be interrupted if it takes too much time...
}
rescue Timeout::Error
puts 'That took too long, exiting...'
end
@louishuyng
louishuyng / number_to_social.rb
Last active November 2, 2023 08:24
Number To Social
def number_to_social(number)
return number_with_delimiter(number) if number < 10_000
number_to_human(number,
precision: 1,
round_mode: :down,
significant: false,
format: "%n%u",
units: {thousand: "K", million: "M", billion: "B"}
)
@louishuyng
louishuyng / rails7_new_features.rb
Last active October 20, 2023 16:27
Rails 7 New Features
## Inquiry
"production".inquiry.production? # True
"active".inquiry.inactive? # False
## Normalizes
class User < ApplicationRecord
normalizes :email, with: ->(email) { email.strip.downcase }
end
## Generate Token For
@louishuyng
louishuyng / one_transaction_per_one_obj.rb
Created October 21, 2023 05:30
One transaction per one Object DDD
class OrdersService
def call(command)
case command
when BatchOfCommands
batch(command.commands)
when ConfirmCommand
confirm(command)
when SetDeliveryMethodCommand
set_delivery(command)
# ...
@louishuyng
louishuyng / domain_class.rb
Created October 21, 2023 05:36
Domain Class Using Struct
class Terms < Struct.new(
:invoice_due_at,
:credit_note,
:release,
:optional_reminder1,
:optional_reminder2
)
end
Terms.new(
@louishuyng
louishuyng / process_manager_event.rb
Created October 23, 2023 13:46
Process Manager Event
class CapturingProcess < ApplicationJob
prepend RailsEventStore::AsyncHandler
class State < ActiveRecord::Base
self.table_name = "capturing_process_state"
serialize :data
def self.get_by_order_number(order_number)
transaction do
lock.find_or_create_by(order_number: order_number).tap do |s|
@louishuyng
louishuyng / aggregate_root.rb
Created October 24, 2023 15:28
Aggregate Root
class Product
include AggregateRoot
def register(store_id:, sku:)
apply(ProductRegistered.new(data: {
store_id: store_id,
sku: sku,
}))
end
@louishuyng
louishuyng / ruby_monkey_patching_using_module.rb
Created November 11, 2023 06:36
Ruby Monkey Patching Using Module
module M
def test_method_with_module
"Test from M"
end
end
class C
def test_method
"Test from C"
end
@louishuyng
louishuyng / main.rb
Last active November 11, 2023 07:03
Ruby Runtime Feature Changes
p = Person.new
p.refresh # => (...)
Person.start_trace
p.refresh # => (...)
# -> refresh: 0.500 s.
Person.end_trace
p.refresh # => (...)
@louishuyng
louishuyng / track_call_stack.rb
Created November 13, 2023 10:57
Track class Stack rails
#!/usr/local/bin/ruby
require 'rubygems'
require 'call_stack'
require 'pp'
class Test
def foo
bar
end