Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
hara-y-u / sequential_id.rb
Last active June 8, 2024 07:53
Scoped Sequential ID Concern for Rails Models
# Usage:
# This module adds single scoped sequential id on AR model.
# In your model, include this module like:
# include SequentialId[:number, scope: :user_id]
module SequentialId
def self.[](column_name, scope:)
options = Struct.new(:column_name, :scope)
Module.new do
extend ActiveSupport::Concern
include SequentialId
@hara-y-u
hara-y-u / soc_with_custom_callbacks.rb
Last active January 9, 2025 14:24
Separation of Concerns with Rails ActiveRecord custom callbacks
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
define_model_callbacks :comment_update, only: :after
end
end
class Post
@hara-y-u
hara-y-u / week_index_in_month.rb
Created January 10, 2025 05:15
Calculate week index in month / Rubyで特定日が何番目の週か計算
require "date"
# Days from day one to first saturday are result in index 1
def week_index_in_month(date)
first_day_of_month = Date.new(date.year, date.month, 1)
((date.day + first_day_of_month.wday) / 7.0).ceil
end
# Days from day one to seven are result in index 1
def week_index_in_month(date)