Skip to content

Instantly share code, notes, and snippets.

@zkan
Created January 22, 2026 09:57
Show Gist options
  • Select an option

  • Save zkan/5e29a6beb7bb56c4a0f4e4e9042868a7 to your computer and use it in GitHub Desktop.

Select an option

Save zkan/5e29a6beb7bb56c4a0f4e4e9042868a7 to your computer and use it in GitHub Desktop.
Demo on how Active Record in Rails works
SCHEMA = {
users: [:id, :email, :name]
}
class MiniRecord
def self.columns
table = (self.name.downcase + "s").to_sym
SCHEMA[table]
end
# Callback invoked whenever a subclass of the current class is created.
# Ref: https://apidock.com/ruby/Class/inherited
def self.inherited(subclass)
cols = subclass.columns || []
cols.each do |col|
# Defines an instance method in the receiver.
# Ref: https://apidock.com/ruby/Module/define_method
subclass.define_method(col) do
@attributes ||= {}
@attributes[col]
end
subclass.define_method("#{col}=") do |value|
@attributes ||= {}
@attributes[col] = value
end
end
end
def self.before_save(method_name)
@before_save_callbacks ||= []
@before_save_callbacks << method_name
end
def self.before_save_callbacks
@before_save_callbacks || []
end
def save
self.class.before_save_callbacks.each do |cb|
# Invokes the method identified by symbol, passing it any arguments specified.
# Ref: https://apidock.com/ruby/Object/send
send(cb)
end
puts "💾 Saving to database..."
puts " Data: #{@attributes.inspect}"
end
end
class User < MiniRecord
before_save :normalize_email
def normalize_email
self.email = email.downcase if email
puts "🔧 before_save: normalize_email"
end
end
u = User.new
u.email = "demo@rails.com"
u.name = "Mini Rails"
puts u.email
puts u.name
u.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment