# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
# Subscribe to a specific room
room = Room.find(params[:room_id])
# Controller responding with Turbo Stream
class PostsController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
class UserSearchQuery
def initialize(relation = User.all)
@relation = relation
end
def call(params)
class UserRegistrationForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :email, :string
attribute :name, :string
# Create table migration
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :email, null: false, index: { unique: true }
t.string :name, null: false
# spec/factories/users.rb
FactoryBot.define do
factory :user do
sequence(:email) { |n| "user#{n}@example.com" }
name { Faker::Name.name }
password { 'password123' }
# Basic exception handling
begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
result = nil
# Basic matching
email = "user@example.com"
email =~ /@/ # => 4 (position of match)
email.match?(/@/) # => true
# Capture groups
module Api
module V1
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_user, only: [:show, :update, :destroy]
<%# Fragment caching - caches rendered HTML %>
<% cache @product do %>
<h1><%= @product.name %></h1>
<p><%= @product.description %></p>
<p>Price: $<%= @product.price %></p>
<% end %>
# Map - transform elements
[1, 2, 3, 4].map { |n| n * 2 } # => [2, 4, 6, 8]
['alice', 'bob'].map(&:upcase) # => ['ALICE', 'BOB']
users.map(&:email) # => ['alice@example.com', ...]
# Select/Reject - filter elements
# app/validators/order_validator.rb
class OrderValidator < ActiveModel::Validator
def validate(record)
validate_order_total(record)
validate_items_availability(record)
validate_shipping_address(record)