Ruby Snippets
Ruby and Rails code patterns
Blocks and Iterators
rubyRuby blocks and iteration patterns
# Basic block usage
numbers = [1, 2, 3, 4, 5]
# Each block
numbers.each do |num|
puts num
end
# Map with block
squares = numbers.map { |num| num ** 2 }
# Select with block
even = numbers.select { |num| num.even? }
# Custom method with block
def custom_iterator
yield if block_given?
end
custom_iterator { puts "Block executed!" }Classes and Modules
rubyObject-oriented programming in Ruby
module Printable
def print_info
puts "#{self.class}: #{self.to_s}"
end
end
class Person
include Printable
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def to_s
"#{name} (#{age} years old)"
end
def self.create_adult(name)
new(name, 18)
end
end
person = Person.new("John", 30)
person.print_infoMetaprogramming
rubyDynamic programming with Ruby
class DynamicMethods
# Define methods dynamically
[:foo, :bar, :baz].each do |method_name|
define_method(method_name) do |arg|
puts "Called #{method_name} with #{arg}"
end
end
# Method missing
def method_missing(name, *args)
if name.to_s =~ /^find_by_(.*)/
attribute = $1
puts "Finding by #{attribute} with value #{args.first}"
else
super
end
end
end
obj = DynamicMethods.new
obj.foo("test")
obj.find_by_name("John")Active Record Patterns
rubyCommon Rails Active Record operations
# Model definition
class User < ApplicationRecord
has_many :posts
validates :email, presence: true, uniqueness: true
scope :active, -> { where(status: 'active') }
def self.search(query)
where("name LIKE ? OR email LIKE ?", "%#{query}%", "%#{query}%")
end
end
# Usage examples
user = User.create!(name: 'John', email: 'john@example.com')
# Associations
user.posts.create!(title: 'Hello World')
# Scopes and queries
active_users = User.active
search_results = User.search('john')
# Eager loading
users_with_posts = User.includes(:posts).where(status: 'active')