### Controller Test Example Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md A controller test for the `UsersController`, demonstrating how to set up a fixture user, make a GET request to the show action, and assert the response status and content. ```ruby # Controller test class UsersControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:one) # Fixture end test "should get show" do get user_url(@user) assert_response :success assert_select 'h1', @user.name end end ``` -------------------------------- ### Rails Testing Setup and Fixtures Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Covers the basic setup for Rails testing, including environment configuration, loading the Rails environment, and using fixtures for test data. It also highlights the `use_transactional_tests` setting for automatic test rollbacks. ```ruby # test/test_helper.rb or spec/rails_helper.rb ENV['RAILS_ENV'] ||= 'test' require_relative '../config/environment' require 'rails/test_help' class ActiveSupport::TestCase # Setup fixtures fixtures :all # Transactional tests (automatic rollback) self.use_transactional_tests = true end ``` -------------------------------- ### Rails Routing Example Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows a basic example of defining routes in `config/routes.rb` to map URLs to controller actions. ```ruby # config/routes.rb defines URL patterns Rails.application.routes.draw do get '/users/:id', to: 'users#show' # Creates params[:id] available in controller end ``` -------------------------------- ### Rails Server Commands Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to start the Rails development server, including options to specify a different port or bind to all network interfaces. ```bash # Server commands rails server rails server -p 3001 # Different port rails server -b 0.0.0.0 # Bind to all interfaces ``` -------------------------------- ### ActiveRecord Connection Management Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Configuration example for managing database connections in `config/database.yml`, including pool size and timeouts. ```ruby # Database connection pool configuration # config/database.yml production: adapter: mysql2 pool: 25 # Maximum connections timeout: 5000 reaping_frequency: 10 # Seconds between reaping dead connections ``` -------------------------------- ### Integration Test Example Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md An integration test simulating a user login flow. It performs a GET request to the login page, a POST request to submit credentials, and follows the redirect to verify the dashboard. ```ruby # Integration test class UserFlowsTest < ActionDispatch::IntegrationTest test "login and browse site" do get "/login" assert_response :success post "/login", params: { email: 'user@example.com', password: 'secret' } follow_redirect! assert_response :success assert_select 'h1', 'Dashboard' end end ``` -------------------------------- ### Asset Fingerprinting Example Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the concept of asset fingerprinting in production, where assets are given unique hashes in their filenames to facilitate caching and cache-busting. ```html # Fingerprinting in production # application-908e25f4bf641868d8683022a5b62f54.js ``` -------------------------------- ### Performance Profiling with Benchmark Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Provides an example of using Benchmark.ms to measure the execution time of a block of code, typically used within a controller action to identify performance bottlenecks. ```ruby class ApplicationController < ActionController::Base around_action :profile_request def profile_request result = nil time = Benchmark.ms { result = yield } Rails.logger.info "#{controller_name}##{action_name} took #{time}ms" result end end ``` -------------------------------- ### Rack Interface Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates how Rack serves as the common interface between web servers and Ruby frameworks like Rails. ```ruby # Rack provides common interface between web servers and Ruby frameworks # Rails.application is a Rack application ``` -------------------------------- ### Service Object Pattern in Rails Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md An example of the Service Object pattern, encapsulating business logic for user registration into a reusable class. ```ruby class UserRegistrationService def initialize(user_params) @user_params = user_params end def call user = User.new(@user_params) if user.save UserMailer.welcome(user).deliver_later CreateDefaultSettings.new(user).call Result.new(success: true, user: user) else Result.new(success: false, errors: user.errors) end end end ``` -------------------------------- ### Controller Filters and Actions Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the use of `before_action` filters for executing code before an action and a sample controller action. ```ruby # Rails creates new controller instance per request # Before filters run first before_action :authenticate_user! before_action :set_user, only: [:show, :edit, :update] def show # Action logic here # Instance variables available to views @user = User.find(params[:id]) end ``` -------------------------------- ### Query Object Pattern in Rails Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md An example of the Query Object pattern, encapsulating query logic for retrieving recently active users. ```ruby class RecentActiveUsersQuery def initialize(relation = User.all) @relation = relation end def call(days_ago: 7) @relation .where(active: true) .where('last_login_at > ?', days_ago.days.ago) .order(last_login_at: :desc) end end ``` -------------------------------- ### Form Object Pattern in Rails Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md An example of the Form Object pattern using `ActiveModel::Model` for handling form input, validation, and persistence. ```ruby class RegistrationForm include ActiveModel::Model attr_accessor :email, :password, :terms_accepted validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :password, length: { minimum: 8 } validates :terms_accepted, acceptance: true def save return false unless valid? User.create!(email: email, password: password) end end ``` -------------------------------- ### ApplicationRecord Base Class Configuration Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the setup of a custom base class for all models in a Rails application, inheriting from ActiveRecord::Base and including global model configurations like a custom SQL sanitization method. ```ruby # All models inherit from ApplicationRecord instead of ActiveRecord::Base class ApplicationRecord < ActiveRecord::Base self.abstract_class = true # Global model configurations def self.sanitize_sql_like(string, escape_character = "\") pattern = Regexp.union(escape_character, "%", "_") string.gsub(pattern) { |x| [escape_character, x].join } end end ``` -------------------------------- ### Active Record Model Test Example Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md An example of a model test for the `User` model, asserting that a user cannot be saved without an email and checking for the presence of an error message. ```ruby # Model test class UserTest < ActiveSupport::TestCase test "should not save user without email" do user = User.new assert_not user.save assert_includes user.errors[:email], "can't be blank" end end ``` -------------------------------- ### ActiveRecord Query Interface Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates chaining ActiveRecord query methods, including lazy loading and eager loading with `includes`. ```ruby # Lazy loading - queries execute only when needed User.where(active: true) # Returns ActiveRecord::Relation .includes(:posts) # Eager loading to prevent N+1 .order(created_at: :desc) .limit(10) .offset(20) # SQL not executed yet .to_a # NOW SQL executes # Query methods that trigger immediate execution: # .first, .last, .find, .find_by, .count, .sum, .average, .minimum, .maximum ``` -------------------------------- ### ActionCable Channel Subscription and Broadcasting Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates the implementation of an ActionCable channel for real-time communication, including subscribing to a specific room and broadcasting messages to connected clients. ```ruby # app/channels/chat_channel.rb class ChatChannel < ApplicationCable::Channel def subscribed stream_from "chat_#{params[:room]}" end def receive(data) ActionCable.server.broadcast("chat_#{params[:room]}", data) end end ``` ```ruby # Broadcasting from anywhere ActionCable.server.broadcast("chat_general", { message: "Hello" }) ``` -------------------------------- ### SQL Query Analysis with EXPLAIN ANALYZE Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to use the EXPLAIN ANALYZE command via ActiveRecord to analyze the execution plan and performance of SQL queries against the database. ```ruby ActiveRecord::Base.connection.execute("EXPLAIN ANALYZE SELECT * FROM users") ``` -------------------------------- ### Rails Routes Commands Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates commands for viewing and filtering application routes, useful for understanding URL patterns and controller actions. ```bash # Routes rails routes rails routes -g user # Grep for 'user' rails routes -c UsersController ``` -------------------------------- ### Rails Tasks Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Lists available Rails tasks for project management, code analysis, and environment information. ```bash rails -T # List all tasks rails stats # Code statistics rails notes # Show TODO, FIXME comments rails about # Environment info ``` -------------------------------- ### Rails Console Commands Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Lists commands for accessing the Rails console, including options for running in a sandbox mode and connecting directly to the database console. ```bash # Console commands rails console rails console --sandbox rails dbconsole ``` -------------------------------- ### Sprockets Asset Inclusion Directives Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates Sprockets directives for managing JavaScript and CSS assets. Includes examples for requiring specific files, including all files in a directory, and self-inclusion. ```javascript # app/assets/javascripts/application.js //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . # Include all files in directory //= require_self # Include this file's content ``` ```css # app/assets/stylesheets/application.scss /* *= require_self *= require_tree . */ @import "bootstrap"; # Using Sass @import ``` -------------------------------- ### FAT Model Anti-pattern and Refactoring Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Highlights the 'FAT Model' anti-pattern where models have too many responsibilities, and suggests refactoring into single-responsibility classes. ```ruby # FAT Models - BAD class User < ApplicationRecord # Too many responsibilities def send_welcome_email UserMailer.welcome(self).deliver_later end def export_to_csv CSV.generate do |csv| # ... end end def calculate_subscription_price # Complex pricing logic end end # BETTER - Single Responsibility class User < ApplicationRecord # Only data and simple business logic end class UserExporter def to_csv(users) # CSV logic end end class SubscriptionPricer def calculate(user) # Pricing logic end end ``` -------------------------------- ### FAT Controller Anti-pattern and Refactoring Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the 'FAT Controller' anti-pattern where controllers handle too much logic, and shows a refactored version using a Service Object. ```ruby # FAT Controllers - BAD class UsersController < ApplicationController def create @user = User.new(user_params) if @user.save UserMailer.welcome(@user).deliver_later @user.profile.create!(bio: 'New user') TeamNotifier.new_member(@user.team, @user) Analytics.track('user_registered', user_id: @user.id) redirect_to @user else render :new end end end # BETTER - Thin controller with service class UsersController < ApplicationController def create result = UserRegistrationService.new(user_params).call if result.success? redirect_to result.user else @user = User.new(user_params) @user.errors = result.errors render :new end end end ``` -------------------------------- ### Rails Query Caching and Low-level Caching Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Explains Rails' built-in query caching within a request and demonstrates low-level caching using `Rails.cache.fetch` for data persistence. ```ruby # Query Caching (within request) User.find(1) # Database query User.find(1) # Cached, no query # Low-level caching Rails.cache.fetch("user_#{id}", expires_in: 12.hours) do User.find(id) end ``` -------------------------------- ### Rails Assets Management Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Commands for managing application assets, including precompilation, cleaning, and clearing cached assets. ```bash rails assets:precompile rails assets:clean rails assets:clobber ``` -------------------------------- ### Rails Middleware Stack Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Lists common middleware components in a typical Rails application and their execution order. ```ruby # View with: rails middleware # Common middleware in order: Rack::Sendfile ActionDispatch::Static ActionDispatch::Executor ActiveSupport::Cache::Strategy::LocalCache::Middleware Rack::Runtime ActionDispatch::RequestId Rails::Rack::Logger ActionDispatch::ShowExceptions ActionDispatch::DebugExceptions ActionDispatch::RemoteIp ActionDispatch::Reloader ActionDispatch::Callbacks ActiveRecord::Migration::CheckPending ActionDispatch::Cookies ActionDispatch::Session::CookieStore ActionDispatch::Flash Rack::Head Rack::ConditionalGet Rack::ETag ``` -------------------------------- ### Rails Directory Structure Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the standard directory layout of a Rails application, outlining the purpose of each directory and key configuration files. ```shell app/ ├── assets/ # CSS, JavaScript, images ├── channels/ # Action Cable channels (WebSockets) ├── controllers/ # Request handlers ├── helpers/ # View helpers ├── jobs/ # Background jobs (ActiveJob) ├── mailers/ # Email handlers ├── models/ # Business logic & data └── views/ # Templates (ERB, HAML, etc.) config/ ├── application.rb # Main app configuration ├── database.yml # Database settings ├── routes.rb # URL routing rules ├── environments/ # Environment-specific settings │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers/ # Run on app boot └── locales/ # i18n translations db/ ├── migrate/ # Database migrations ├── schema.rb # Current DB structure └── seeds.rb # Initial data lib/ ├── assets/ # Custom assets └── tasks/ # Rake tasks public/ # Static files served directly test/ or spec/ # Test files vendor/ # Third-party code Gemfile # Dependencies declaration ``` -------------------------------- ### N+1 Query Problem and Eager Loading Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates the N+1 query problem in Rails and how to solve it using eager loading with `includes` for improved performance. ```ruby # BAD - N+1 queries @posts = Post.all @posts.each do |post| puts post.user.name # Query for each post's user end # GOOD - Eager loading @posts = Post.includes(:user) # 2 queries total @posts = Post.includes(:user, comments: :author) # Nested eager loading ``` -------------------------------- ### Ruby ActionController Response Handling Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows various methods for constructing and sending responses in Rails controllers, including rendering different formats, redirects, and file downloads. ```ruby class PostsController < ApplicationController def show @post = Post.find(params[:id]) respond_to do |format| format.html # Renders show.html.erb format.json { render json: @post } format.xml { render xml: @post } format.js # Renders show.js.erb for AJAX end # Response methods: head :ok # Empty response with status redirect_to posts_path # 302 redirect redirect_to @post, status: :moved_permanently # 301 redirect render status: :not_found # 404 with template render plain: "Text" # Plain text response render json: { key: 'value' } render xml: @post.to_xml send_file '/path/to/file' # File download send_data pdf_content, filename: 'report.pdf' end end ``` -------------------------------- ### Ruby ActionView Template Resolution Process Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Explains the order in which Rails searches for view templates based on controller, action, format, and handler, including inheritance. ```ruby # Rails looks for templates in this order: # 1. app/views/controller_name/action_name.format.handler # 2. app/views/application/action_name.format.handler # 3. Inheritance chain views # Example for PostsController#show with format.html: # 1. app/views/posts/show.html.erb # 2. app/views/posts/show.html.haml # 3. app/views/posts/show.html.slim # 4. app/views/application/show.html.erb (if exists) ``` -------------------------------- ### Routing Information Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates how to access and display routing information within a Rails application using Rake tasks and the application's URL helpers. ```ruby Rails.application.routes.url_helpers.users_path ``` ```bash rake routes | grep user ``` ```bash rails routes -c UsersController ``` -------------------------------- ### Ruby ActionView Helper Methods and Form Builders Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates common view helper methods for generating HTML links, images, and formatted text, as well as using form builders for creating forms with fields and nested attributes. ```ruby # View helpers available globally link_to "Profile", user_path(@user), class: "btn" image_tag "logo.png", alt: "Logo" content_tag :div, "Content", class: "wrapper" truncate @post.body, length: 100 pluralize @users.count, "user" number_to_currency @product.price time_ago_in_words @post.created_at # Form builders <%= form_with model: @user, local: true do |form| <%= form.text_field :name %> <%= form.email_field :email %> <%= form.collection_select :role_id, Role.all, :id, :name %> <%= form.fields_for :profile do |profile_form| <%= profile_form.text_field :bio %> <% end %> <% end %> ``` -------------------------------- ### Configuring Middleware Stack Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to integrate the custom `RequestTimer` middleware into the Rails application's middleware stack using `config.middleware.use`, `insert_before`, `insert_after`, and `delete`. ```ruby # config/application.rb config.middleware.use RequestTimer config.middleware.insert_before ActionDispatch::Static, RequestTimer config.middleware.insert_after Rack::Sendfile, RequestTimer config.middleware.delete ActionDispatch::Static # Remove middleware ``` -------------------------------- ### Asset Path Helper in SCSS Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates using the `image-url` helper within SCSS files to reference images, which automatically handles fingerprinting and path generation. ```css # In SCSS .logo { background-image: image-url('logo.png'); # Handles fingerprinting } ``` -------------------------------- ### Ruby Callbacks Execution Order Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Details the sequence of callback methods executed during create, update, and destroy operations in a Rails application. ```ruby # CREATE operation callbacks order: before_validation after_validation before_save around_save before_create around_create after_create after_save after_commit/after_rollback # UPDATE operation callbacks order: before_validation after_validation before_save around_save before_update around_update after_update after_save after_commit/after_rollback # DESTROY operation callbacks order: before_destroy around_destroy after_destroy after_commit/after_rollback ``` -------------------------------- ### Concerns for Shared Behavior in Rails Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates the use of `ActiveSupport::Concern` to share behavior, specifically tracking creation and update events, across models. ```ruby module Trackable extend ActiveSupport::Concern included do after_create :track_creation after_update :track_update end def track_creation ActivityLog.create!(action: 'created', trackable: self) end def track_update ActivityLog.create!(action: 'updated', trackable: self) end end ``` -------------------------------- ### Rails Console Debugging Techniques Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Provides essential commands and techniques for debugging within the Rails console, including reloading, sandbox mode, logging, and inspection. ```ruby # Reload console without restarting reload! # Sandbox mode (rollback on exit) rails console --sandbox # View SQL for queries ActiveRecord::Base.logger = Logger.new(STDOUT) # Inspect object without all attributes user = User.first user.attributes.slice('id', 'email', 'name') # Get all methods specific to model User.instance_methods(false) # View source location User.instance_method(:some_method).source_location # Benchmark queries Benchmark.ms { User.all.to_a } # Explain query plan User.where(active: true).explain ``` -------------------------------- ### Rails Testing Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Executes Rails tests, allowing for testing of the entire suite, specific models, or even individual lines of code. ```bash rails test rails test test/models rails test test/models/user_test.rb rails test test/models/user_test.rb:15 # Specific line ``` -------------------------------- ### Finding Missing Database Indexes Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md A Ruby script to identify potential missing database indexes on foreign key columns within a Rails application. ```ruby # Check missing indexes # In Rails console ActiveRecord::Base.connection.tables.each do |table| indexes = ActiveRecord::Base.connection.indexes(table) columns = ActiveRecord::Base.connection.columns(table) # Find foreign keys without indexes columns.select { |c| c.name.ends_with?('_id') }.each do |column| unless indexes.any? { |i| i.columns.include?(column.name) } puts "Missing index on #{table}.#{column.name}" end end end ``` -------------------------------- ### Content Security Policy Configuration Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Configures the Content Security Policy for a Rails application to enhance security by specifying allowed sources for content. ```ruby Rails.application.config.content_security_policy do |policy| policy.default_src :self, :https policy.font_src :self, :https, :data policy.img_src :self, :https, :data policy.object_src :none policy.script_src :self, :https policy.style_src :self, :https end ``` -------------------------------- ### Rails Database Management Commands Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Provides essential Rake commands for managing the Rails application's database, including creating, migrating, rolling back, seeding, and resetting the database. ```bash # Database commands rails db:create rails db:migrate rails db:rollback rails db:seed rails db:reset # drop, create, migrate, seed ``` -------------------------------- ### Rails Generate Commands Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md A collection of common Rails generator commands for creating models, controllers, migrations, and scaffolds, essential for scaffolding new features and database structures. ```bash # Generate commands rails generate model User name:string email:string rails generate controller Users index show rails generate migration AddAgeToUsers age:integer rails generate scaffold Post title:string body:text ``` -------------------------------- ### MySQL Full-Text Search Scope Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Provides a Ruby scope for performing full-text searches on the 'name' and 'bio' columns in MySQL using the `MATCH AGAINST` syntax. ```ruby class User < ApplicationRecord # Full-text search (MySQL) scope :search, ->(term) { where("MATCH(name, bio) AGAINST (?)", term) } end ``` -------------------------------- ### Ruby Associations and Loading Strategies Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates defining associations (has_many, has_one, belongs_to) and using scopes, counter caches, and various eager loading strategies (includes, eager_load, preload, joins) in Rails models. ```ruby class User < ApplicationRecord has_many :posts has_many :comments, through: :posts has_one :profile belongs_to :company, optional: true # Rails 5 requires belongs_to by default # Scopes for reusable queries scope :active, -> { where(active: true) } scope :recent, -> { order(created_at: :desc) } # Counter cache for performance has_many :posts, counter_cache: true end # Eager loading strategies: User.includes(:posts) # LEFT OUTER JOIN, separate queries User.eager_load(:posts) # LEFT OUTER JOIN, single query User.preload(:posts) # Multiple queries, no JOIN User.joins(:posts) # INNER JOIN, doesn't load associations ``` -------------------------------- ### Custom Request Timer Middleware Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Details the creation of a custom Rack middleware `RequestTimer` that calculates and adds the request processing duration to the response headers as `X-Runtime`. ```ruby # lib/middleware/request_timer.rb class RequestTimer def initialize(app) @app = app end def call(env) start_time = Time.current status, headers, response = @app.call(env) # Pass to next middleware duration = Time.current - start_time headers['X-Runtime'] = duration.to_s [status, headers, response] end end ``` -------------------------------- ### Asset Pipeline Helper Usage in Views Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to use Rails view helpers like `stylesheet_link_tag`, `javascript_include_tag`, `image_tag`, and `asset_path` to reference assets, including handling fingerprinting and data attributes. ```html # In views <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> <%= image_tag 'logo.png', class: 'logo' %> <%= asset_path 'application.js' %> # Returns path with fingerprint ``` -------------------------------- ### Ruby ActiveRecord Transaction Management Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates how to use ActiveRecord transactions to ensure data consistency by grouping multiple database operations that should either all succeed or all fail. ```ruby # Transactions ensure data consistency ActiveRecord::Base.transaction do user = User.create!(name: "John") profile = user.create_profile!(bio: "Developer") # If any operation fails, entire transaction rolls back end ``` -------------------------------- ### Rails API Mode Application Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the creation and structure of a Rails application specifically configured for API-only use, highlighting the differences in the base controller and the absence of view-related functionalities. ```bash # Generate API-only application # rails new my_api --api ``` ```ruby class ApplicationController < ActionController::API # Lighter controller without view rendering # No sessions, cookies, flash, assets end ``` -------------------------------- ### Russian Doll Caching in Rails Views Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates the implementation of Russian Doll Caching in Rails views to cache fragments of HTML based on model objects. ```ruby %cache @post do <%= @post.title %> %cache @post.author do <%= @post.author.name %> end end ``` -------------------------------- ### Debugging with Byebug Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates how to use the Byebug gem for interactive debugging within a Ruby method. It allows developers to set breakpoints and inspect the application's state during execution. ```ruby def some_method byebug # Breakpoint # Interactive debugger starts here end ``` -------------------------------- ### Ruby ActiveRecord Migration Mechanics Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to define database schema changes using ActiveRecord migrations, including creating tables, defining columns with types and constraints, adding indexes, and managing rollback-safe changes. ```ruby class CreateUsers < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.string :email, null: false t.string :name t.integer :age t.decimal :balance, precision: 10, scale: 2 t.boolean :active, default: true t.text :bio t.json :preferences # MySQL 5.7+ / PostgreSQL t.references :company, foreign_key: true t.timestamps # created_at, updated_at end add_index :users, :email, unique: true add_index :users, [:company_id, :active] # Composite index end end # Rollback-safe migrations def up add_column :users, :status, :string end def down remove_column :users, :status end ``` -------------------------------- ### Strong Parameters for User Input Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates the use of strong parameters in Rails to permit specific attributes for user creation or updates, including nested attributes and arrays, preventing mass-assignment vulnerabilities. ```ruby def user_params params.require(:user).permit(:name, :email, roles: [], profile_attributes: [:bio, :avatar]) end ``` -------------------------------- ### Ruby ActionController Request Object Details Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates accessing information from the Request object within a Rails controller, including HTTP method, headers, body, IP address, and parameters. ```ruby class UsersController < ApplicationController def create # Request object provides: request.method # GET, POST, PUT, DELETE, etc. request.headers # HTTP headers hash request.body # Raw request body request.remote_ip # Client IP request.xhr? # AJAX request? request.format # :html, :json, :xml request.ssl? # HTTPS? request.local? # Local request? request.path # /users/new request.fullpath # /users/new?sort=name request.original_url # http://example.com/users/new?sort=name # Params object: params # ActionController::Parameters params.require(:user).permit(:name, :email) # Strong parameters end end ``` -------------------------------- ### PostgreSQL Array Column Scope Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Creates a Ruby scope to query PostgreSQL array columns. It checks if a given tag exists within the 'tags' array column. ```ruby class Product < ApplicationRecord # Array columns (PostgreSQL) scope :with_tag, ->(tag) { where(":tag = ANY(tags)", tag: tag) } end ``` -------------------------------- ### Memory Profiling with MemoryProfiler Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates how to use the MemoryProfiler gem to analyze memory allocation and usage within a specific block of Ruby code, helping to identify memory leaks or inefficiencies. ```ruby require 'memory_profiler' report = MemoryProfiler.report do # Code to profile end report.pretty_print ``` -------------------------------- ### CSRF Protection Configuration Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to configure Cross-Site Request Forgery (CSRF) protection in Rails controllers, including the default `protect_from_forgery` and options for skipping it or using alternative strategies. ```ruby # CSRF Protection (enabled by default) class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Rails 5 default # Alternatives: # protect_from_forgery with: :null_session # API controllers # protect_from_forgery with: :reset_session # Skip for specific actions skip_before_action :verify_authenticity_token, only: [:webhook] end ``` -------------------------------- ### Rails Logging Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows various ways to use Rails logger for different log levels (debug, info, error) and how to apply custom log tags for better organization and filtering of log messages. ```ruby Rails.logger.debug "Variable value: #{@variable.inspect}" Rails.logger.info "Processing user #{user.id}" Rails.logger.error "Failed to process: #{e.message}" ``` ```ruby Rails.logger.tagged('USER_IMPORT') do Rails.logger.info "Starting import" # All logs within block are tagged end ``` -------------------------------- ### Pessimistic and Optimistic Locking Strategies Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Illustrates two locking strategies: pessimistic locking using `.lock` which translates to `SELECT ... FOR UPDATE`, and optimistic locking using `.with_lock` which acquires a lock for the duration of the block. ```ruby user = User.lock.find(1) # SELECT ... FOR UPDATE (pessimistic) user = User.find(1) user.with_lock do # Locks during block execution user.update!(balance: user.balance + 100) end ``` -------------------------------- ### ActiveRecord Attributes API with Custom Types Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Shows how to define attributes for Rails models using the Attributes API, including specifying data types, default values, and custom type casting. ```ruby class Product < ApplicationRecord attribute :price_in_cents, :integer attribute :published_at, :datetime, default: -> { Time.current } # Custom type attribute :preferences, PreferencesType.new end ``` -------------------------------- ### PostgreSQL JSONB Query Scope Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Defines a Ruby scope for querying JSONB columns in PostgreSQL. It checks if a specific feature key exists and is set to true within the 'features' JSONB column. ```ruby class Product < ApplicationRecord # JSONB queries (PostgreSQL) scope :with_feature, ->(feature) { where("features @> ?", { feature => true }.to_json) } end ``` -------------------------------- ### Nested Transactions and Rollback Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Demonstrates the use of nested transactions with `requires_new: true` to manage savepoints. An `ActiveRecord::Rollback` within an inner transaction only affects that inner transaction, leaving the outer one intact. ```ruby User.transaction do User.create!(name: "Parent") User.transaction(requires_new: true) do User.create!(name: "Child") raise ActiveRecord::Rollback # Only rolls back inner transaction end end ``` -------------------------------- ### SQL Injection Prevention Techniques Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Highlights the importance of preventing SQL injection by using parameterized queries (e.g., `User.where("name = ?", params[:name])` or `User.where(name: params[:name])`) and warns against direct string interpolation. ```ruby # SQL Injection Prevention # GOOD - Parameterized queries User.where("name = ?", params[:name]) User.where(name: params[:name]) # BAD - Direct interpolation User.where("name = '#{params[:name]}'") # VULNERABLE! ``` -------------------------------- ### XSS Prevention in Rails Views Source: https://github.com/aliraza-lakhani/aas/blob/master/RAILS5_INTERNALS_GUIDE.md Explains how Rails automatically escapes HTML output by default to prevent Cross-Site Scripting (XSS) attacks. It shows the difference between safe (`<%= @user.bio %>`) and unsafe raw output (`<%== @user.bio %>` or `<%= raw @user.bio %>`). ```html # XSS Prevention # Views automatically escape output <%= @user.bio %> # HTML escaped <%== @user.bio %> # Raw output (dangerous) <%= raw @user.bio %> # Raw output (dangerous) <%= @user.bio.html_safe %> # Marked as safe (use carefully) ``` -------------------------------- ### Rails Error Page Content Source: https://github.com/aliraza-lakhani/aas/blob/master/public/422.html Displays a common error message indicating a rejected change, often due to access restrictions, and suggests checking logs for details. ```html The change you wanted was rejected (422) . The change you wanted was rejected. =================================== Maybe you tried to change something you didn't have access to. If you are the application owner check the logs for more information. ``` -------------------------------- ### Rails Default Error Page Styling Source: https://github.com/aliraza-lakhani/aas/blob/master/public/500.html Provides CSS styles for a default error page in a Rails application. It defines the layout, colors, and fonts for displaying error messages to users. ```css .rails-default-error-page { background-color: #EFEFEF; color: #2E2F30; text-align: center; font-family: arial, sans-serif; margin: 0; } .rails-default-error-page div.dialog { width: 95%; max-width: 33em; margin: 4em auto 0; } .rails-default-error-page div.dialog > div { border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #BBB; border-top: #B00100 solid 4px; border-top-left-radius: 9px; border-top-right-radius: 9px; background-color: white; padding: 7px 12% 0; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } .rails-default-error-page h1 { font-size: 100%; color: #730E15; line-height: 1.5em; } .rails-default-error-page div.dialog > p { margin: 0 0 1em; padding: 1em; background-color: #F7F7F7; border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #999; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-color: #DADADA; color: #666; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } ``` -------------------------------- ### Rails Default Error Page Styling Source: https://github.com/aliraza-lakhani/aas/blob/master/public/422.html Provides CSS styles for the default error page in Rails applications, including layout, typography, and box shadows for dialogs and messages. ```css .rails-default-error-page { background-color: #EFEFEF; color: #2E2F30; text-align: center; font-family: arial, sans-serif; margin: 0; } .rails-default-error-page div.dialog { width: 95%; max-width: 33em; margin: 4em auto 0; } .rails-default-error-page div.dialog > div { border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #BBB; border-top: #B00100 solid 4px; border-top-left-radius: 9px; border-top-right-radius: 9px; background-color: white; padding: 7px 12% 0; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } .rails-default-error-page h1 { font-size: 100%; color: #730E15; line-height: 1.5em; } .rails-default-error-page div.dialog > p { margin: 0 0 1em; padding: 1em; background-color: #F7F7F7; border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #999; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-color: #DADADA; color: #666; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } ``` -------------------------------- ### Generic Error Message Source: https://github.com/aliraza-lakhani/aas/blob/master/public/500.html A standard error message indicating that an unexpected issue occurred within the application. It advises application owners to check logs for more details. ```text We're sorry, but something went wrong. ====================================== If you are the application owner check the logs for more information. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.