### Install Guides Dependencies and Generate HTML Source: https://guides.rubyonrails.org/v7.0/contributing_to_ruby_on_rails.html Installs necessary gems for generating HTML guides and then generates the HTML guides for a specific language. Use `bundle config --delete without` to undo. ```bash # only install gems necessary for the guides. To undo run: bundle config --delete without $ bundle install --without job cable storage ujs test db $ cd guides/ $ bundle exec rake guides:generate:html GUIDES_LANGUAGE=it-IT ``` -------------------------------- ### Generate All HTML Guides Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Command to generate all HTML guides. Ensure you are in the 'guides' directory and have Bundler installed. ```bash $ bundle exec rake guides:generate ``` ```bash $ bundle exec rake guides:generate:html ``` -------------------------------- ### Rails::Server#start Method Source: https://guides.rubyonrails.org/v7.0/initialization.html Defines the startup behavior for the Rails server, including signal trapping, directory creation, and development caching setup. ```Ruby module Rails class Server < ::Rack::Server def start(after_stop_callback = nil) trap(:INT) { exit } create_tmp_directories setup_dev_caching log_to_stdout if options[:log_stdout] super() # ... end private def setup_dev_caching if options[:environment] == "development" Rails::DevCaching.enable_by_argument(options[:caching]) end end def create_tmp_directories %w(cache pids sockets).each do |dir_to_make| FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make)) end end def log_to_stdout wrapped_app # touch the app so the logger is set up console = ActiveSupport::Logger.new(STDOUT) console.formatter = Rails.logger.formatter console.level = Rails.logger.level unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT) Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) end end end end ``` -------------------------------- ### List Available Homebrew Services on macOS Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html After installing services with Homebrew, use this command to list all services that can be managed. This helps in identifying services to start. ```bash $ brew services list ``` -------------------------------- ### Start Standalone Cable Server Source: https://guides.rubyonrails.org/v7.0/action_cable_overview.html Use a binstub to start the standalone Action Cable server on a specific port. ```bash #!/bin/bash bundle exec puma -p 28080 cable/config.ru ``` -------------------------------- ### Start a Specific Homebrew Service on macOS Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Replace 'mysql' with the name of the service you wish to start. This command is used to manually start individual services installed via Homebrew. ```bash $ brew services start mysql ``` -------------------------------- ### Install All Dependencies with Homebrew on macOS Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Use this command to install all required services and tools using Homebrew's bundle feature. Ensure Homebrew is installed first. ```bash $ brew bundle ``` -------------------------------- ### PostgreSQL EXPLAIN output example Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html This is an example of the `EXPLAIN` output for a query executed on a PostgreSQL database. ```text EXPLAIN for: SELECT "customers".* FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id" WHERE "customers"."id" = $1 [["id", 1]] QUERY PLAN ------------------------------------------------------------------------------ Nested Loop (cost=4.33..20.85 rows=4 width=164) -> Index Scan using customers_pkey on customers (cost=0.15..8.17 rows=1 width=164) Index Cond: (id = '1'::bigint) -> Bitmap Heap Scan on orders (cost=4.18..12.64 rows=4 width=8) Recheck Cond: (customer_id = '1'::bigint) -> Bitmap Index Scan on index_orders_on_customer_id (cost=0.00..4.18 rows=4 width=0) Index Cond: (customer_id = '1'::bigint) (7 rows) ``` -------------------------------- ### Generate Specific HTML Guide Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Command to generate only a specific Markdown guide file. This is useful for testing changes to a single guide. ```bash $ touch my_guide.md $ bundle exec rake guides:generate ONLY=my_guide ``` -------------------------------- ### MySQL/MariaDB EXPLAIN output example Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html This is an example of the `EXPLAIN` output for a query executed on a MySQL or MariaDB database. ```text EXPLAIN for: SELECT `customers`.* FROM `customers` INNER JOIN `orders` ON `orders`.`customer_id` = `customers`.`id` WHERE `customers`.`id` = 1 +----+-------------+------------+-------+---------------+---------+---------+-------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+---------------+---------+---------+-------+------+-------------+ | 1 | SIMPLE | customers | const | PRIMARY | PRIMARY | 4 | const | 1 | | | 1 | SIMPLE | orders | ALL | NULL | NULL | NULL | NULL | 1 | Using where | +----+-------------+------------+-------+---------------+---------+---------+-------+------+-------------+ 2 rows in set (0.00 sec) ``` -------------------------------- ### Install All Dependencies on Arch Linux Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Installs required packages for Ruby on Rails development on Arch Linux using pacman. Includes MariaDB (as MySQL is not supported), PostgreSQL, Redis, Memcached, and multimedia tools. Also initializes and starts services. ```bash $ sudo pacman -S sqlite mariadb libmariadbclient mariadb-clients postgresql postgresql-libs redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler yarn libxml2 $ sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql $ sudo systemctl start redis mariadb memcached ``` -------------------------------- ### Interactive Example for Create and Update Callbacks Source: https://guides.rubyonrails.org/v7.0/active_record_callbacks.html This interactive example shows the output when creating and updating a User record using the defined `after_create_commit` and `after_update_commit` callbacks. ```irb irb> @user = User.create # prints nothing irb> @user.save # updating @user User was saved to database ``` -------------------------------- ### Install Action Mailbox Migrations and Migrate Database Source: https://guides.rubyonrails.org/v7.0/action_mailbox_basics.html Install the necessary migrations for InboundEmail records and ensure your database is up-to-date. ```bash $ bin/rails action_mailbox:install $ bin/rails db:migrate ``` -------------------------------- ### Fragment Cache Logging Example (Verbose) Source: https://guides.rubyonrails.org/v7.0/configuring.html Example of verbose logging for fragment cache reads and writes when `enable_fragment_cache_logging` is true. ```text Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms) Rendered messages/_message.html.erb in 1.2 ms [cache hit] Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms) Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] ``` -------------------------------- ### Fragment Cache Logging Example (Default) Source: https://guides.rubyonrails.org/v7.0/configuring.html Example of default logging for fragment cache reads and writes when `enable_fragment_cache_logging` is false. ```text Rendered messages/_message.html.erb in 1.2 ms [cache hit] Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] ``` -------------------------------- ### Create Article for Partial Layout Example Source: https://guides.rubyonrails.org/v7.0/action_view_overview.html This snippet demonstrates creating a new Article record, which is used in the subsequent partial layout example. Ensure the Article model is defined. ```ruby Article.create(body: 'Partial Layouts are cool!') ``` -------------------------------- ### Example Payment Configuration YAML Source: https://guides.rubyonrails.org/v7.0/configuring.html A sample `config/payment.yml` file demonstrating environment-specific configurations. ```yaml production: environment: production merchant_id: production_merchant_id public_key: production_public_key private_key: production_private_key development: environment: sandbox merchant_id: development_merchant_id public_key: development_public_key private_key: development_private_key ``` -------------------------------- ### Generate Kindle Guides Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Command to generate guides specifically formatted for the Kindle device. ```bash $ bundle exec rake guides:generate:kindle ``` -------------------------------- ### Generate HTML Guides in a Different Language Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Command to generate guides in a language other than English. Place the language-specific Markdown files in a subdirectory under 'source'. ```bash $ bundle exec rake guides:generate GUIDES_LANGUAGE=es ``` -------------------------------- ### Example CHANGELOG Entry Source: https://guides.rubyonrails.org/v7.0/contributing_to_ruby_on_rails.html An example of a CHANGELOG entry, including a summary, code example, and issue reference. Use this format when adding or removing features, fixing bugs, or adding deprecations. ```markdown * Summary of a change that briefly describes what was changed. You can use multiple lines and wrap them at around 80 characters. Code examples are ok, too, if needed: class Foo def bar puts 'baz' end end You can continue after the code example, and you can attach the issue number. Fixes #1234. *Your Name* ``` -------------------------------- ### Verify Rails Installation Source: https://guides.rubyonrails.org/v7.0/getting_started.html After installation, verify that Rails is correctly set up by checking its version. A successful output will display the installed Rails version, such as 'Rails 7.0.0'. ```bash $ rails --version ``` -------------------------------- ### Install Project Dependencies with Bundler Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Install all project dependencies using Bundler. This command installs gems required for the project, including those for Active Record tests. ```bash $ bundle install ``` -------------------------------- ### Installing Webpacker Source: https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html Provides the command to install Webpacker after adding it to the Gemfile. This command sets up Webpacker in your Rails application. ```shell $ bin/rails webpacker:install ``` -------------------------------- ### Start Rails Server Source: https://guides.rubyonrails.org/v7.0/command_line.html Command to start the Puma server for a Rails application. ```bash $ bin/rails server => Booting Puma... ``` -------------------------------- ### Install All Dependencies on Ubuntu Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Installs essential development tools and services for Ruby on Rails on Ubuntu using apt-get. This includes databases, caching, image/video processing, and PDF tools. ```bash $ sudo apt-get update $ sudo apt-get install sqlite3 libsqlite3-dev mysql-server libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools libxml2-dev # Install Yarn $ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - $ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list $ sudo apt-get install yarn ``` -------------------------------- ### Install All Dependencies on FreeBSD Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Installs necessary development packages for Ruby on Rails on FreeBSD using pkg. Includes database clients/servers, caching, and multimedia tools. Redis can be installed via pkg or ports. ```bash $ pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgresql11-server memcached imagemagick ffmpeg mupdf yarn libxml2 # portmaster databases/redis ``` -------------------------------- ### Install Webpacker in an Existing Rails Project Source: https://guides.rubyonrails.org/v7.0/webpacker.html Add the `webpacker` gem to your `Gemfile`, run `bundle install`, and then execute the Webpacker installation command. ```bash bundle install bin/rails webpacker:install ``` -------------------------------- ### Install Rails Gem Source: https://guides.rubyonrails.org/v7.0/getting_started.html Use RubyGems to install the Rails framework. This command fetches and installs the latest stable version of Rails. ```bash $ gem install rails ``` -------------------------------- ### Start Active Storage (NPM Package) Source: https://guides.rubyonrails.org/v7.0/active_storage_overview.html Import and start Active Storage when using it as an npm package in your JavaScript application. ```javascript import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start() ``` -------------------------------- ### Builder RSS Feed Example Source: https://guides.rubyonrails.org/v7.0/action_view_overview.html Provides a full-length example of generating an RSS feed using the Builder library, including channel and item elements. ```ruby xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do xml.channel do xml.title(@feed_title) xml.link(@url) xml.description "Basecamp: Recent items" xml.language "en-us" xml.ttl "40" for item in @recent_items xml.item do xml.title(item_title(item)) xml.description(item_description(item)) if item_description(item) xml.pubDate(item_pubDate(item)) xml.guid(@person.firm.account.url + @recent_items.url(item)) xml.link(@person.firm.account.url + @recent_items.url(item)) xml.tag!("dc:creator", item.author_name) if item_has_creator?(item) end end end end ``` -------------------------------- ### Configure Primary Database Source: https://guides.rubyonrails.org/v7.0/active_record_multiple_databases.html Example of a basic single database configuration in `database.yml`. ```yaml production: database: my_primary_database adapter: mysql2 username: root password: <%= ENV['ROOT_PASSWORD'] %> ``` -------------------------------- ### Example Rails Middleware Stack Source: https://guides.rubyonrails.org/v7.0/rails_on_rack.html An example output of the `bin/rails middleware` command, illustrating the default middlewares in a freshly generated Rails application. This shows the order and types of middlewares used. ```text use Rack::Sendfile use ActionDispatch::Static use ActionDispatch::Executor use ActiveSupport::Cache::Strategy::LocalCache::Middleware use Rack::Runtime use Rack::MethodOverride use ActionDispatch::RequestId use ActionDispatch::RemoteIp use Sprockets::Rails::QuietAssets use Rails::Rack::Logger use ActionDispatch::ShowExceptions use WebConsole::Middleware use ActionDispatch::DebugExceptions use ActionDispatch::ActionableExceptions use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::Migration::CheckPending use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash use ActionDispatch::ContentSecurityPolicy::Middleware use Rack::Head use Rack::ConditionalGet use Rack::ETag use Rack::TempfileReaper run MyApp::Application.routes ``` -------------------------------- ### Install All Dependencies on Fedora or CentOS Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Installs necessary development packages for Ruby on Rails on Fedora or CentOS using dnf. Includes database, caching, and multimedia tools. Also covers Yarn installation. ```bash $ sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached imagemagick ffmpeg mupdf libxml2-devel # Install Yarn # Use this command if you do not have Node.js installed $ curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash - # If you have Node.js installed, use this command instead $ curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/apt/sources.list.d/yarn.repo $ sudo dnf install yarn ``` -------------------------------- ### Live Streaming Lyrics Example Source: https://guides.rubyonrails.org/v7.0/action_controller_overview.html An example demonstrating how to stream song lyrics line by line in a karaoke fashion using ActionController::Live. This ensures each line is sent only after the previous one has been 'sung'. ```ruby class LyricsController < ActionController::Base include ActionController::Live def show response.headers['Content-Type'] = 'text/event-stream' song = Song.find(params[:id]) song.each do |line| response.stream.write line.lyrics sleep line.num_beats end ensure response.stream.close end end ``` -------------------------------- ### CSS Manifest File Example Source: https://guides.rubyonrails.org/v7.0/asset_pipeline.html Example of a CSS manifest file using Sprockets directives to include self and all CSS files in the current directory. ```css /* ... *= require_self *= require_tree . */ ``` -------------------------------- ### Simulate GET Request with Headers Source: https://guides.rubyonrails.org/v7.0/testing.html Demonstrates how to simulate a GET request to a specific resource, including passing custom HTTP headers. Useful for testing authentication or referer checks. ```ruby get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" } ``` -------------------------------- ### Setup the Database Source: https://guides.rubyonrails.org/v7.0/active_record_migrations.html Creates the database, loads the schema, and initializes it with seed data. This command is used for setting up a new development environment. ```bash $ bin/rails db:setup ``` -------------------------------- ### GET Request to Patients URL Source: https://guides.rubyonrails.org/v7.0/routing.html Example of an incoming GET request for a specific patient URL. ```text GET /patients/17 ``` -------------------------------- ### JavaScript Manifest File Example Source: https://guides.rubyonrails.org/v7.0/asset_pipeline.html Example of a JavaScript manifest file using Sprockets directives to include necessary libraries and all JavaScript files in the current directory. ```javascript // ... //= require rails-ujs //= require turbolinks //= require_tree . ``` -------------------------------- ### Start Rails Server Source: https://guides.rubyonrails.org/v7.0/getting_started.html Run this command in your Rails application's root directory to start the development server. For Windows users, use 'ruby bin\rails server'. ```bash $ bin/rails server ``` -------------------------------- ### Rack::Server#start Method Source: https://guides.rubyonrails.org/v7.0/initialization.html Initiates the Rack server startup process, handling options like warnings, load paths, debugging, and daemonization. ```Ruby module Rack class Server def start &blk if options[:warn] $-w = true end if includes = options[:include] $LOAD_PATH.unshift(*includes) end if library = options[:require] require library end if options[:debug] $DEBUG = true require "pp" p options[:server] pp wrapped_app pp app end check_pid! if options[:pid] # Touch the wrapped app, so that the config.ru is loaded before # daemonization (i.e. before chdir, etc). handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do wrapped_app end daemonize_app if options[:daemonize] write_pid if options[:pid] trap(:INT) do if server.respond_to?(:shutdown) server.shutdown else exit end end server.run wrapped_app, options, &blk end end end ``` -------------------------------- ### Require config/application.rb Source: https://guides.rubyonrails.org/v7.0/initialization.html The `config/environment.rb` file starts by requiring `config/application.rb`. This is a fundamental step in setting up the Rails environment. ```ruby require_relative "application" ``` -------------------------------- ### RDoc Example: Attribute Reader Source: https://guides.rubyonrails.org/v7.0/api_documentation_guidelines.html Example of an RDoc comment for an attribute reader method. Comments should start with an uppercase letter and follow standard punctuation rules. ```ruby # Declares an attribute reader backed by an internally-named # instance variable. def attr_internal_reader(*attrs) # ... end ``` -------------------------------- ### Refactored Controller Tests with Setup and Teardown Source: https://guides.rubyonrails.org/v7.0/testing.html Demonstrates refactoring controller tests using `setup` and `teardown` callbacks to reduce duplication and manage instance variables and cache clearing. ```ruby require "test_helper" class ArticlesControllerTest < ActionDispatch::IntegrationTest # called before every single test setup do @article = articles(:one) end # called after every single test teardown do # when controller is using cache it may be a good idea to reset it afterwards Rails.cache.clear end test "should show article" do # Reuse the @article instance variable from setup get article_url(@article) assert_response :success end test "should destroy article" do assert_difference("Article.count", -1) do delete article_url(@article) end assert_redirected_to articles_path end test "should update article" do patch article_url(@article), params: { article: { title: "updated" } } assert_redirected_to article_path(@article) # Reload association to fetch updated data and assert that title is updated. @article.reload assert_equal "updated", @article.title end end ``` -------------------------------- ### Example: Generate Greetings Controller with Hello Action Source: https://guides.rubyonrails.org/v7.0/command_line.html Generates a `Greetings` controller with a `hello` action. This command also sets up the route for the action and creates the necessary view and test files. ```bash $ bin/rails generate controller Greetings hello ``` -------------------------------- ### Application Template for Devise Installation Source: https://guides.rubyonrails.org/v7.0/generators.html An application template script that conditionally installs Devise, prompts for the user model name, and runs necessary setup commands. ```ruby # template.rb if yes?("Would you like to install Devise?") gem "devise" devise_model = ask("What would you like the user model to be called?", default: "User") end after_bundle do if devise_model generate "devise:install" generate "devise", devise_model rails_command "db:migrate" end git add: ".", commit: %(-m 'Initial commit') end ``` -------------------------------- ### config/boot.rb for Bundler setup Source: https://guides.rubyonrails.org/v7.0/initialization.html Initializes Bundler by setting the `BUNDLE_GEMFILE` environment variable and requiring `bundler/setup` to configure the gem load path. ```ruby ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. ``` -------------------------------- ### Get Substring from Position Source: https://guides.rubyonrails.org/v7.0/active_support_core_extensions.html Returns the substring starting from a given position. Supports positive, negative, and out-of-bounds indices, returning nil if the start position is beyond the string length. ```ruby "hello".from(0) # => "hello" "hello".from(2) # => "llo" "hello".from(-2) # => "lo" "hello".from(10) # => nil ``` -------------------------------- ### Simple YAML Translation Example Source: https://guides.rubyonrails.org/v7.0/i18n.html A basic example of a translation string in YAML format. This defines a 'hello' key that maps to the 'Hello world' string in the :en locale. ```yaml en: hello: "Hello world" ``` -------------------------------- ### Relative File Path Example Source: https://guides.rubyonrails.org/v7.0/api_documentation_guidelines.html Demonstrates the correct way to specify file paths relative to the application root. ```Text config/routes.rb # YES routes.rb # NO RAILS_ROOT/config/routes.rb # NO ``` -------------------------------- ### Get Beginning and End of Week Source: https://guides.rubyonrails.org/v7.0/active_support_core_extensions.html Returns the dates for the beginning and end of the week. Weeks default to starting on Monday, but this can be customized. ```ruby d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 d.beginning_of_week # => Mon, 03 May 2010 d.beginning_of_week(:sunday) # => Sun, 02 May 2010 d.end_of_week # => Sun, 09 May 2010 d.end_of_week(:sunday) # => Sat, 08 May 2010 ``` -------------------------------- ### Key Rotation Configuration Example Source: https://guides.rubyonrails.org/v7.0/active_record_encryption.html Example configuration for key rotation using a list of primary keys. The last key is used for encrypting new content, while all keys are tried for decryption. ```yaml active_record_encryption: primary_key: - a1cc4d7b9f420e40a337b9e68c5ecec6 # Previous keys can still decrypt existing content - bc17e7b413fd4720716a7633027f8cc4 # Active, encrypts new content key_derivation_salt: a3226b97b3b2f8372d1fc6d497a0c0d3 ``` -------------------------------- ### Install Webpacker in a New Rails Project Source: https://guides.rubyonrails.org/v7.0/webpacker.html Add the `--webpack` flag to the `rails new` command to include Webpacker from the start. ```bash rails new myapp --webpack ``` -------------------------------- ### Reset the Database Source: https://guides.rubyonrails.org/v7.0/active_record_migrations.html Drops the existing database and then sets it up again from scratch. This is equivalent to running `db:drop` followed by `db:setup`. ```bash $ bin/rails db:reset ``` -------------------------------- ### Markdown Headings Structure Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Demonstrates the expected heading structure in Markdown for guide titles, sections, and subsections. The generated HTML will start with h2 tags. ```markdown Guide Title =========== Section ------- ### Sub Section ``` -------------------------------- ### Rackup Command Help Source: https://guides.rubyonrails.org/v7.0/rails_on_rack.html Displays help information for the `rackup` command, useful for understanding its various options. ```bash $ rackup --help ``` -------------------------------- ### Creating a Specific Database Source: https://guides.rubyonrails.org/v7.0/active_record_multiple_databases.html Demonstrates how to create a specific database, such as the 'animals' database, using a dedicated Rails command. ```bash bin/rails db:create:animals ``` -------------------------------- ### Getting All Parent Modules with `module_parents` Source: https://guides.rubyonrails.org/v7.0/active_support_core_extensions.html The `module_parents` method returns an array of all containing modules, starting from the immediate parent up to `Object`. This is useful for traversing the module hierarchy. ```Ruby module X module Y module Z end end end M = X::Y::Z X::Y::Z.module_parents # => [X::Y, X, Object] M.module_parents # => [X::Y, X, Object] ``` -------------------------------- ### Install JavaScript Dependencies Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Install JavaScript dependencies using Yarn. Ensure Yarn is installed prior to running this command. ```bash $ yarn install ``` -------------------------------- ### Create Database with bin/rails db:create Source: https://guides.rubyonrails.org/v7.0/command_line.html Creates the application's database. ```bash bin/rails db:create ``` -------------------------------- ### Controller with Responders Source: https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html Example of a controller using respond_to and respond_with after adding the responders gem. ```ruby class UsersController < ApplicationController respond_to :html, :json def show @user = User.find(params[:id]) respond_with @user end end ``` -------------------------------- ### Home View Index Template Source: https://guides.rubyonrails.org/v7.0/i18n.html Renders a "Hello World" heading and displays the flash notice. ```erb

Hello World

<%= flash[:notice] %>

``` -------------------------------- ### Verify SQLite3 Installation Source: https://guides.rubyonrails.org/v7.0/getting_started.html Confirm that SQLite3 is installed and accessible in your system's load path. The command should output the installed version number. ```bash $ sqlite3 --version ``` -------------------------------- ### Specify Start ID for find_in_batches Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Retrieves records starting from a specific ID using the `start` option. Useful for resuming interrupted batch processes. ```ruby Customer.find_in_batches(batch_size: 2500, start: 5000) do |customers| export.add_customers(customers) end ``` -------------------------------- ### MySQL/MariaDB EXPLAIN output for eager loading Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Example `EXPLAIN` output for a query involving eager loading on MySQL/MariaDB, showing separate plans for the main query and the included associations. ```text EXPLAIN for: SELECT `customers`.* FROM `customers` WHERE `customers`.`id` = 1 +----+-------------+-----------+-------+---------------+---------+---------+-------+------+------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra| +----+-------------+-----------+-------+---------------+---------+---------+-------+------+------+ | 1 | SIMPLE | customers | const | PRIMARY | PRIMARY | 4 | const | 1 | | +----+-------------+-----------+-------+---------------+---------+---------+-------+------+------+ 1 row in set (0.00 sec) EXPLAIN for: SELECT `orders`.* FROM `orders` WHERE `orders`.`customer_id` IN (1) +----+-------------+--------+------+---------------+------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+------+---------------+------+---------+------+------+-------------+ | 1 | SIMPLE | orders | ALL | NULL | NULL | NULL | NULL | 1 | Using where | +----+-------------+--------+------+---------------+------+---------+------+------+-------------+ 1 row in set (0.00 sec) ``` -------------------------------- ### Define Models for Form Examples Source: https://guides.rubyonrails.org/v7.0/form_helpers.html Defines simple ApplicationRecord models for demonstrating form helpers. ```ruby class City < ApplicationRecord end class Person < ApplicationRecord belongs_to :city end ``` -------------------------------- ### PostgreSQL EXPLAIN output for eager loading Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Example `EXPLAIN` output for a query involving eager loading on PostgreSQL, showing the SQL statements executed and their respective query plans. ```text Customer Load (0.3ms) SELECT "customers".* FROM "customers" WHERE "customers"."id" = $1 [["id", 1]] Order Load (0.3ms) SELECT "orders".* FROM "orders" WHERE "orders"."customer_id" = $1 [["customer_id", 1]] => EXPLAIN for: SELECT "customers".* FROM "customers" WHERE "customers"."id" = $1 [["id", 1]] QUERY PLAN ---------------------------------------------------------------------------------- Index Scan using customers_pkey on customers (cost=0.15..8.17 rows=1 width=164) Index Cond: (id = '1'::bigint) (2 rows) ``` -------------------------------- ### Install RubyGems Dependencies Source: https://guides.rubyonrails.org/v7.0/contributing_to_ruby_on_rails.html Installs all the required RubyGems for the Rails project. ```bash $ bundle install ``` -------------------------------- ### Example: Generate CreditCards Controller Source: https://guides.rubyonrails.org/v7.0/command_line.html Generates a `CreditCards` controller with `open`, `debit`, `credit`, `close` actions. This includes creating associated view files and tests. ```bash $ bin/rails generate controller CreditCards open debit credit close ``` -------------------------------- ### Run Tests with Full Backtrace Source: https://guides.rubyonrails.org/v7.0/testing.html Demonstrates how to run tests and include the full backtrace in the output by using the `-b` or `--backtrace` command-line argument. This is useful for debugging framework-level issues. ```shell $ bin/rails test -b test/models/article_test.rb ``` -------------------------------- ### Install Bundler Gem Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Install or update the Bundler gem to manage project dependencies. ```bash $ gem install bundler $ gem update bundler ``` -------------------------------- ### Rails Server Initialization Source: https://guides.rubyonrails.org/v7.0/rails_on_rack.html Shows how `bin/rails server` creates a `Rack::Server` object and starts the web server. This code is part of the `Rails::Server` class, which inherits from `Rack::Server`. ```ruby Rails::Server.new.tap do |server| require APP_PATH Dir.chdir(Rails.application.root) server.start end ``` ```ruby class Server < ::Rack::Server def start # ... super end end ``` -------------------------------- ### Fingerprinted CSS Filename Example Source: https://guides.rubyonrails.org/v7.0/asset_pipeline.html An example of a CSS filename after fingerprinting, where a hash of the content is appended. ```text global-908e25f4bf641868d8683022a5b62f54.css ``` -------------------------------- ### Configure PostgreSQL User for Testing (Linux/BSD) Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Set up a superuser for PostgreSQL on Linux or BSD systems using the current user. ```bash $ sudo -u postgres createuser --superuser $USER ``` -------------------------------- ### Navigate to Application Directory Source: https://guides.rubyonrails.org/v7.0/getting_started.html After creating the application, change your current directory to the newly created application folder using the `cd` command. ```bash cd blog ``` -------------------------------- ### View Plugin Generator Options Source: https://guides.rubyonrails.org/v7.0/engines.html Run this command to see all available options for the plugin generator. ```bash $ rails plugin --help ``` -------------------------------- ### Configure Multiple Databases Source: https://guides.rubyonrails.org/v7.0/active_record_multiple_databases.html Example of a `database.yml` configuration for multiple databases, including primary, replicas, and a separate database for 'animals' with its own replica. ```yaml production: primary: database: my_primary_database username: root password: <%= ENV['ROOT_PASSWORD'] %> adapter: mysql2 primary_replica: database: my_primary_database username: root_readonly password: <%= ENV['ROOT_READONLY_PASSWORD'] %> adapter: mysql2 replica: true animals: database: my_animals_database username: animals_root password: <%= ENV['ANIMALS_ROOT_PASSWORD'] %> adapter: mysql2 migrations_paths: db/animals_migrate animals_replica: database: my_animals_database username: animals_readonly password: <%= ENV['ANIMALS_READONLY_PASSWORD'] %> adapter: mysql2 replica: true ``` -------------------------------- ### Print all defined initializers Source: https://guides.rubyonrails.org/v7.0/command_line.html Lists all initializers in the order they are invoked by Rails. ```bash bin/rails initializers ``` -------------------------------- ### Engine Initialization File Source: https://guides.rubyonrails.org/v7.0/engines.html The `lib/blorgh.rb` file requires the engine's engine file and defines the base module. It can also be used for global configuration. ```ruby require "blorgh/engine" module Blorgh end ``` -------------------------------- ### S3 CORS Configuration Example Source: https://guides.rubyonrails.org/v7.0/active_storage_overview.html Example CORS configuration for Amazon S3 to allow direct upload requests from your application. ```json [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT" ], "AllowedOrigins": [ "https://www.example.com" ], "ExposeHeaders": [ "Origin", "Content-Type", "Content-MD5", "Content-Disposition" ], "MaxAgeSeconds": 3600 } ] ``` -------------------------------- ### Direct Rendering with Instance Variables and Flash Source: https://guides.rubyonrails.org/v7.0/layouts_and_rendering.html Demonstrates how to directly render a template (e.g., 'index') and populate instance variables and flash messages when a record is not found, avoiding an extra browser round trip. ```ruby def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? @books = Book.all flash.now[:alert] = "Your book was not found" render "index" end end ``` -------------------------------- ### Example Log Entry of Cookie Theft Source: https://guides.rubyonrails.org/v7.0/security.html This is an example of what an attacker's web server access log might look like after a successful cookie theft attempt using the previous XSS example. It shows the stolen cookie appended to the requested URL. ```text GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2 ``` -------------------------------- ### Wrapped JSON Parameters Example Source: https://guides.rubyonrails.org/v7.0/action_controller_overview.html This example shows how JSON parameters are wrapped with a key based on the controller name when `wrap_parameters` is active. ```json { name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } } ``` -------------------------------- ### Google Cloud Storage CORS Configuration Example Source: https://guides.rubyonrails.org/v7.0/active_storage_overview.html Example CORS configuration for Google Cloud Storage to permit direct upload requests. ```json [ { "origin": ["https://www.example.com"], "method": ["PUT"], "responseHeader": ["Origin", "Content-Type", "Content-MD5", "Content-Disposition"], "maxAgeSeconds": 3600 } ] ``` -------------------------------- ### Rack::Handler::Puma Run Method Source: https://guides.rubyonrails.org/v7.0/initialization.html Illustrates the `run` method for the Puma server handler, showing how it configures and launches the Puma server with the provided application and options. ```ruby module Rack module Handler module Puma # ... def self.run(app, options = {}) conf = self.config(app, options) events = options.delete(:Silent) ? ::Puma::Events.strings : ::Puma::Events.stdio launcher = ::Puma::Launcher.new(conf, :events => events) yield launcher if block_given? begin launcher.run rescue Interrupt puts "* Gracefully stopping, waiting for requests to finish" launcher.stop puts "* Goodbye!" end end # ... end end end ``` -------------------------------- ### Install Engine Migrations Source: https://guides.rubyonrails.org/v7.0/engines.html Command to copy migration files from the 'blorgh' engine into the application's `db/migrate` directory. This ensures the engine's database schema is created in the application. ```bash $ bin/rails blorgh:install:migrations ``` -------------------------------- ### Old Rails Query String Cache Busting Example Source: https://guides.rubyonrails.org/v7.0/asset_pipeline.html An example of how older Rails versions appended a date-based query string for cache busting. ```text /stylesheets/global.css?1309495796 ``` -------------------------------- ### Configuring Reloadable Code with `to_prepare` Source: https://guides.rubyonrails.org/v7.0/autoloading_and_reloading_constants.html Shows how to correctly configure reloadable constants within initializers by wrapping the code in a `to_prepare` block, ensuring it runs on boot and after each reload. ```ruby # config/initializers/api_gateway_setup.rb Rails.application.config.to_prepare do ApiGateway.endpoint = "https://example.com" # CORRECT end ``` -------------------------------- ### Azure Storage CORS Configuration Example Source: https://guides.rubyonrails.org/v7.0/active_storage_overview.html Example CORS configuration for Azure Storage, specifying allowed origins, methods, and headers for direct uploads. ```xml https://www.example.com PUT Origin, Content-Type, Content-MD5, x-ms-blob-content-disposition, x-ms-blob-type 3600 ``` -------------------------------- ### Cache Key Example Source: https://guides.rubyonrails.org/v7.0/caching_with_rails.html An example of a cache key generated by Rails for a view fragment. The template tree digest changes if the view fragment is modified. ```text views/products/index:bea67108094918eeba42cd4a6e786901/products/1 ``` -------------------------------- ### Interactive Example for after_save_commit Source: https://guides.rubyonrails.org/v7.0/active_record_callbacks.html This interactive example demonstrates the behavior of the `after_save_commit` alias when creating and updating a User record, showing the output of the associated callback. ```irb irb> @user = User.create # creating a User User was saved to database irb> @user.save # updating @user User was saved to database ``` -------------------------------- ### Parallel Testing with Setup and Teardown Hooks Source: https://guides.rubyonrails.org/v7.0/testing.html Use `parallelize_setup` and `parallelize_teardown` hooks for tasks that need to run after forking and before closing processes, such as managing multiple databases. ```ruby class ActiveSupport::TestCase parallelize_setup do |worker| # setup databases end parallelize_teardown do |worker| # cleanup databases end parallelize(workers: :number_of_processors) end ``` -------------------------------- ### Add Collection Route with GET Verb Source: https://guides.rubyonrails.org/v7.0/routing.html Defines a 'search' collection route for 'photos' using a `collection` block, recognizing GET requests to `/photos/search`. ```ruby resources :photos do collection do get 'search' end end ``` -------------------------------- ### after_initialize and after_find Callback Execution Source: https://guides.rubyonrails.org/v7.0/active_record_callbacks.html Shows the output when creating a new user and finding an existing user, illustrating when `after_initialize` and `after_find` are triggered. ```irb irb> User.new You have initialized an object! => # irb> User.first You have found an object! You have initialized an object! => # ``` -------------------------------- ### Validate Generated HTML Guides Source: https://guides.rubyonrails.org/v7.0/ruby_on_rails_guides_guidelines.html Command to validate the generated HTML guides. This helps catch issues like duplicate IDs generated from heading titles. ```bash $ bundle exec rake guides:validate ``` -------------------------------- ### Start Rails Development Server Source: https://guides.rubyonrails.org/v7.0/command_line.html Starts the Rails development server, typically used for local development and testing. Access your application via http://localhost:3000. ```bash $ bin/rails server ``` -------------------------------- ### Generate Scaffold with Custom Generator Source: https://guides.rubyonrails.org/v7.0/generators.html Demonstrates running the scaffold generator after configuring custom generators and fallbacks, showing the custom generator being invoked. ```bash $ bin/rails generate scaffold Comment body:text invoke active_record create db/migrate/20230518000000_create_comments.rb create app/models/comment.rb invoke my_test_unit Doing different stuff... invoke resource_route route resources :comments invoke scaffold_controller create app/controllers/comments_controller.rb invoke erb create app/views/comments create app/views/comments/index.html.erb create app/views/comments/edit.html.erb create app/views/comments/show.html.erb create app/views/comments/new.html.erb create app/views/comments/_form.html.erb create app/views/comments/_comment.html.erb invoke resource_route invoke my_test_unit create test/controllers/comments_controller_test.rb create test/system/comments_test.rb invoke helper create app/helpers/comments_helper.rb invoke my_test_unit invoke jbuilder create app/views/comments/index.json.jbuilder create app/views/comments/show.json.jbuilder ``` -------------------------------- ### Get Integer Ordinal Suffix Source: https://guides.rubyonrails.org/v7.0/active_support_core_extensions.html Use `ordinal` to get the ordinal suffix (st, nd, rd, th) for an integer. Handles positive and negative numbers. ```ruby 1.ordinal # => "st" 2.ordinal # => "nd" 53.ordinal # => "rd" 2009.ordinal # => "th" -21.ordinal # => "st" -134.ordinal # => "th" ``` -------------------------------- ### SQL for includes (2 queries) Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html These SQL queries illustrate the efficient loading achieved by `includes`. The first query fetches the books, and the second fetches all associated authors in a single query. ```sql SELECT books.* FROM books LIMIT 10 SELECT authors.* FROM authors WHERE authors.book_id IN (1,2,3,4,5,6,7,8,9,10) ``` -------------------------------- ### Run EXPLAIN on a basic query Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Use `explain` to see the query plan for a simple Active Record query. The output format varies depending on the database adapter. ```ruby Customer.where(id: 1).joins(:orders).explain ``` -------------------------------- ### Add Member Route with GET Verb Source: https://guides.rubyonrails.org/v7.0/routing.html Defines a 'preview' member route for 'photos' using a `member` block, which recognizes GET requests to `/photos/:id/preview`. ```ruby resources :photos do member do get 'preview' end end ``` -------------------------------- ### Install All Railties Migrations Source: https://guides.rubyonrails.org/v7.0/engines.html Command to copy migration files from all installed railties (including engines) into the application's `db/migrate` directory. Use this if you have multiple engines with migrations. ```bash $ bin/rails railties:install:migrations ``` -------------------------------- ### Configure PostgreSQL User for Testing (macOS) Source: https://guides.rubyonrails.org/v7.0/development_dependencies_install.html Set up a superuser for PostgreSQL on macOS using the current user. ```bash $ createuser --superuser $USER ``` -------------------------------- ### Run EXPLAIN with eager loading Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Use `explain` with `includes` to analyze the query plans generated for eager loading. This may result in multiple queries being explained. ```ruby Customer.where(id: 1).includes(:orders).explain ``` -------------------------------- ### Specify Start and Finish IDs with find_each Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Use `:start` and `:finish` options together with `find_each` to process a specific range of records based on their primary key IDs. ```ruby Customer.find_each(start: 2000, finish: 10000) do |customer| NewsMailer.weekly(customer).deliver_now end ``` -------------------------------- ### Specify Start ID with find_each Source: https://guides.rubyonrails.org/v7.0/active_record_querying.html Use the `:start` option with `find_each` to begin processing records from a specific primary key ID, useful for resuming interrupted processes. ```ruby Customer.find_each(start: 2000) do |customer| NewsMailer.weekly(customer).deliver_now end ``` -------------------------------- ### CSRF Protection for JavaScript GET Requests Source: https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html Switch from `get` to `xhr` when testing JavaScript responses to explicitly test an XmlHttpRequest and avoid triggering CSRF protection unexpectedly. ```ruby get :index, format: :js ``` ```ruby xhr :get, :index, format: :js ``` -------------------------------- ### Sample YAML Fixture File Source: https://guides.rubyonrails.org/v7.0/testing.html This is an example of a human-friendly YAML fixture file for defining sample data. Each record is separated by a blank line, and comments can be added using the '#' character. ```yaml # lo & behold! I am a YAML comment! david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development steve: name: Steve Ross Kellock birthday: 1974-09-27 profession: guy with keyboard ``` -------------------------------- ### Get Integer Ordinal String Source: https://guides.rubyonrails.org/v7.0/active_support_core_extensions.html Use `ordinalize` to get the full ordinal string representation of an integer, including the number and its suffix. Handles positive and negative numbers. ```ruby 1.ordinalize # => "1st" 2.ordinalize # => "2nd" 53.ordinalize # => "53rd" 2009.ordinalize # => "2009th" -21.ordinalize # => "-21st" -134.ordinalize # => "-134th" ``` -------------------------------- ### Add Gem Dependency Source: https://guides.rubyonrails.org/v7.0/engines.html Specify a gem dependency that should be installed with the engine during a traditional `gem install`. This is done within the `Gem::Specification` block in the engine's .gemspec file. ```ruby s.add_dependency "moo" ```