### Implement Rails::Server#start Source: https://guides.rubyonrails.org/v8.0/initialization.html Defines the server startup sequence, including signal trapping, directory creation, and logger setup. ```ruby module Rails class Server < ::Rackup::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, STDERR, STDOUT) Rails.logger.broadcast_to(console) end end end end ``` -------------------------------- ### Kamal Initial Server Setup (Shell) Source: https://guides.rubyonrails.org/v8.0/getting_started.html This command initiates the setup process for deploying a Rails application using Kamal. It configures the production server environment, including installing necessary dependencies and preparing the server for the application. ```shell $ bin/kamal setup ``` -------------------------------- ### Solid Cable Adapter Setup Source: https://guides.rubyonrails.org/v8.0/action_cable_overview.html Instructions for installing and configuring the Solid Cable adapter, which uses Active Record and requires manual database configuration. ```APIDOC ## Solid Cable Adapter Setup ### Description The Solid Cable adapter is a database-backed solution that uses Active Record. It has been tested with MySQL, SQLite, and PostgreSQL. Running `bin/rails solid_cable:install` will automatically set up `config/cable.yml` and create `db/cable_schema.rb`. After that, you must manually update `config/database.yml`, adjusting it based on your database. ### Method N/A (Installation and Configuration) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Rails Script Command Examples Source: https://guides.rubyonrails.org/v8.0/2_2_release_notes.html Illustrates various command-line scripts used in Rails development, such as starting the server with Thin, installing plugins with specific revisions, and accessing the Rails console with debugger support. ```Shell script/server script/plugin install -r script/console --debugger ``` -------------------------------- ### Start Rails Server with Rack::Server Source: https://guides.rubyonrails.org/v8.0/rails_on_rack.html Demonstrates how bin/rails server creates and starts a Rack::Server object. This code is executed when starting the Rails development 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 ``` -------------------------------- ### Start Rails Server Source: https://guides.rubyonrails.org/v8.0/command_line.html Use `bin/rails server` to start the development server. Access your application at http://localhost:3000. ```bash $ bin/rails server => Booting Puma... ``` -------------------------------- ### Code Example Formatting Source: https://guides.rubyonrails.org/v8.0/api_documentation_guidelines.html Demonstrates how to format code examples, including indentation, Rails conventions, and inline comments with results. ```APIDOC ## Example Code Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas. For proper rendering, indent code by two spaces from the left margin. The examples themselves should use Rails coding conventions. Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs: ```ruby # Converts a collection of elements into a formatted string by # calling +to_s+ on all elements and joining them. # # Blog.all.to_fs # => "First PostSecond PostThird Post" ``` On the other hand, big chunks of structured documentation may have a separate "Examples" section: ```ruby # ==== Examples # # Person.exists?(5) # Person.exists?('5') # Person.exists?(name: "David") # Person.exists?(name: "David") # Person.exists?(["name LIKE ?", "%#{query}%"]) ``` The results of expressions follow them and are introduced by "# => ", vertically aligned: ```ruby # For checking if an integer is even or odd. # # 1.even? # => false # 1.odd? # => true # 2.even? # => true # 2.odd? # => false ``` If a line is too long, the comment may be placed on the next line: ```ruby # label(:article, :title) # # => # # label(:article, :title, "A short title") # # => # # label(:article, :title, "A short title", class: "title_label") # # => ``` Avoid using any printing methods like `puts` or `p` for that purpose. On the other hand, regular comments do not use an arrow: ```ruby # polymorphic_url(record) # same as comment_url(record) ``` ``` -------------------------------- ### Start the Rails Server Source: https://guides.rubyonrails.org/v8.0/asset_pipeline.html Run the `bin/rails server` command to start the Rails development server. ```bash $ bin/rails server ``` -------------------------------- ### Install Active Storage and Run Migrations Source: https://guides.rubyonrails.org/v8.0/active_storage_overview.html Install Active Storage by running the provided Rails generator and then migrate the database to create the necessary tables: active_storage_blobs, active_storage_attachments, and active_storage_variant_records. ```bash $ bin/rails active_storage:install $ bin/rails db:migrate ``` -------------------------------- ### Generate HTML Rails Guides in a Specific Language Source: https://guides.rubyonrails.org/v8.0/contributing_to_ruby_on_rails.html This command generates the Rails guides in HTML format for a specified language. It requires installing dependencies and navigating to the guides directory. Ensure you have the necessary gems installed. ```bash $ BUNDLE_ONLY=default:doc bundle install $ cd guides/ $ BUNDLE_ONLY=default:doc bundle exec rake guides:generate:html GUIDES_LANGUAGE=it-IT ``` -------------------------------- ### Starting Active Storage (NPM Package) Source: https://guides.rubyonrails.org/v8.0/active_storage_overview.html Initializes Active Storage by importing and starting the library when using the npm package. ```javascript import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start() ``` -------------------------------- ### Create Rails Application Template with Devise Setup (Ruby) Source: https://guides.rubyonrails.org/v8.0/generators.html This Ruby script defines an application template that automates the setup of the Devise gem in a new Rails application. It interactively asks the user if they want to install Devise, prompts for the user model name, adds the gem to the Gemfile, runs Devise generators, performs database migrations, and makes an initial Git commit. ```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 ``` -------------------------------- ### Install Dependencies on Ubuntu Source: https://guides.rubyonrails.org/v8.0/development_dependencies_install.html Commands to install required system packages, Node.js, and Yarn on Ubuntu-based systems. ```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 libvips42 poppler-utils libyaml-dev libffi-dev sudo mkdir -p /etc/apt/keyrings curl --fail --silent --show-error --location https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list sudo apt-get update sudo apt-get install -y nodejs sudo npm install --global yarn ``` -------------------------------- ### Install and Migrate Action Mailbox Source: https://guides.rubyonrails.org/v8.0/action_mailbox_basics.html Commands to install the Action Mailbox framework and run the necessary database migrations to store inbound emails. ```bash bin/rails action_mailbox:install bin/rails db:migrate ``` -------------------------------- ### Manage Services on macOS with Homebrew Source: https://guides.rubyonrails.org/v8.0/development_dependencies_install.html Commands to install, list, and start system services required for Rails development using Homebrew. ```bash brew bundle brew services list brew services start mysql ``` -------------------------------- ### Ruby Option Section Style Example Source: https://guides.rubyonrails.org/v8.0/api_documentation_guidelines.html Presents an alternative documentation style for providing additional details and examples, particularly for options. This style uses a section header like '==== Options' followed by detailed explanations and code examples for each option. ```Ruby # ==== Options # # [+:expires_at+] # The datetime at which the message expires. After this datetime, # verification of the message will fail. # # message = encryptor.encrypt_and_sign("hello", expires_at: Time.now.tomorrow) # encryptor.decrypt_and_verify(message) # => "hello" # # 24 hours later... # encryptor.decrypt_and_verify(message) # => nil ``` -------------------------------- ### Generate Rails Guides Locally Source: https://guides.rubyonrails.org/v8.0/2_2_release_notes.html This command generates the Rails Guides documentation locally within your application. The generated guides are placed in `Rails.root/doc/guides` and can be accessed by opening `Rails.root/doc/guides/index.html` in a web browser. ```bash $ rake doc:guides ``` -------------------------------- ### Install Rails 3 with Gem Source: https://guides.rubyonrails.org/v8.0/3_0_release_notes.html Command to install the Ruby on Rails version 3.0 using the RubyGems package manager. Use sudo if necessary for system-wide installation. ```bash # Use sudo if your setup requires it $ gem install rails ``` -------------------------------- ### Install Ruby on Windows via WSL Source: https://guides.rubyonrails.org/v8.0/install_ruby_on_rails.html Sets up the Windows Subsystem for Linux (WSL) and installs the required Ruby development environment within the Ubuntu distribution. ```bash wsl --install --distribution Ubuntu-24.04 sudo apt update sudo apt install build-essential rustc libssl-dev libyaml-dev zlib1g-dev libgmp-dev curl https://mise.run | sh echo 'eval "$(~/.local/bin/mise activate bash)"' >> ~/.bashrc source ~/.bashrc mise use -g ruby@3 ``` -------------------------------- ### Creating an Article Record Source: https://guides.rubyonrails.org/v8.0/action_view_overview.html Example of creating an article record for demonstration purposes. ```ruby Article.create(body: "Partial Layouts are cool!") ``` -------------------------------- ### Install Ruby on Ubuntu Source: https://guides.rubyonrails.org/v8.0/install_ruby_on_rails.html Installs necessary build dependencies and the Mise version manager on Ubuntu to support Ruby development. ```bash sudo apt update sudo apt install build-essential rustc libssl-dev libyaml-dev zlib1g-dev libgmp-dev git curl https://mise.run | sh echo 'eval "$(~/.local/bin/mise activate)"' >> ~/.bashrc source ~/.bashrc mise use -g ruby@3 ``` -------------------------------- ### Install Dependencies on Fedora or CentOS Source: https://guides.rubyonrails.org/v8.0/development_dependencies_install.html Commands to install required system packages, Node.js, and Yarn on Fedora or CentOS systems. ```bash sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached ImageMagick ffmpeg mupdf libxml2-devel vips poppler-utils sudo dnf install https://rpm.nodesource.com/pub_20/nodistro/repo/nodesource-release-nodistro-1.noarch.rpm -y sudo dnf install nodejs -y --setopt=nodesource-nodejs.module_hotfixes=1 sudo npm install --global yarn ``` -------------------------------- ### Ruby Asset Tag Helper Example (image_tag) Source: https://guides.rubyonrails.org/v8.0/api_documentation_guidelines.html Illustrates documenting framework behavior within the full Rails stack, using `ActionView::Helpers::AssetTagHelper#image_tag` as an example. It shows how the output of `image_tag` can differ when considering the Asset Pipeline, emphasizing that documentation should reflect the user's experience with the complete framework. ```Ruby # image_tag("icon.png") # # => ``` -------------------------------- ### Define Initial Models for `includes` Example Source: https://guides.rubyonrails.org/v8.0/association_basics.html These are the base model definitions used in the `includes` example to demonstrate second-order association eager loading. ```ruby class Supplier < ApplicationRecord has_one :account end class Account < ApplicationRecord belongs_to :supplier belongs_to :representative end class Representative < ApplicationRecord has_many :accounts end ``` -------------------------------- ### Generate Rails Guides Source: https://guides.rubyonrails.org/v8.0/ruby_on_rails_guides_guidelines.html Commands to generate HTML documentation for Rails guides. Supports full generation, selective file processing via the ONLY variable, and language localization. ```shell bundle exec rake guides:generate bundle exec rake guides:generate:html touch my_guide.md bundle exec rake guides:generate ONLY=my_guide bundle exec rake guides:generate GUIDES_LANGUAGE=es ``` -------------------------------- ### Implement Rackup::Server#start Source: https://guides.rubyonrails.org/v8.0/initialization.html Handles server configuration, PID management, and the final execution of the Rack application. ```ruby module Rackup class Server def start(&block) if options[:warn] $-w = true end if includes = options[:include] $LOAD_PATH.unshift(*includes) end Array(options[:require]).each do |library| 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, &block) end end end ``` -------------------------------- ### DRY controller tests with setup and teardown Source: https://guides.rubyonrails.org/v8.0/testing.html Uses setup and teardown callbacks to share article fixtures and manage cache across multiple tests. ```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 ``` -------------------------------- ### Configure Solid Cache Sharding Source: https://guides.rubyonrails.org/v8.0/caching_with_rails.html Example `config/database.yml` demonstrating how to set up multiple cache shard databases for increased scalability. ```yaml # config/database.yml production: cache_shard1: database: cache1_production host: cache1-db cache_shard2: database: cache2_production host: cache2-db cache_shard3: database: cache3_production host: cache3-db ``` -------------------------------- ### Verify Rails Installation in Dev Container Source: https://guides.rubyonrails.org/v8.0/getting_started_with_devcontainer.html This command verifies that the Rails framework is correctly installed within the development container environment. It outputs the installed Rails version, confirming the setup is complete. ```bash $ rails --version Rails 8.0.0 ``` -------------------------------- ### Action Mailbox Example with Callbacks and Processing Source: https://guides.rubyonrails.org/v8.0/action_mailbox_basics.html An example Action Mailbox demonstrating the use of `before_processing` callbacks to validate conditions before email processing. It shows how to bounce emails using `bounced_with` and how to record email data into Active Record models or trigger Action Mailer. ```Ruby # Example of a mailbox processing incoming emails class ForwardsMailbox < ApplicationMailbox before_processing :ensure_user_has_projects def process record_forward end private def ensure_user_has_projects # Check if the 'forwarder' (user) has any projects unless forwarder.projects.any? bounced_with :no_projects_for_forwarder end end def record_forward # Create an Active Record model using email subject and body Project.create!( user: forwarder, subject: mail.subject, body: mail.decoded ) end def forwarder # Find the user associated with the sender's email address User.find_by(email: mail.from) end end ``` -------------------------------- ### Find records in batches starting from a specific ID Source: https://guides.rubyonrails.org/v8.0/active_record_querying.html Combine `batch_size` and `start` options to retrieve records in batches, beginning from a specified ID. This example retrieves batches of 2500 records starting from ID 5000. ```ruby Customer.find_in_batches(batch_size: 2500, start: 5000) do |customers| export.add_customers(customers) end ``` -------------------------------- ### Automating Rails Application Setup with Templates Source: https://guides.rubyonrails.org/v8.0/generators.html Demonstrates a typical template script that scaffolds a model, configures routes, runs migrations, and initializes a git repository. ```ruby generate(:scaffold, "person name:string") route "root to: 'people#index'" rails_command("db:migrate") after_bundle do git :init git add: "." git commit: %Q{ -m 'Initial commit' } end ``` -------------------------------- ### Install Rails Gem Dependencies Source: https://guides.rubyonrails.org/v8.0/contributing_to_ruby_on_rails.html Install the necessary Ruby gems for the Rails project using Bundler. This command should be run after cloning the repository and before starting development. ```bash $ bundle install ``` -------------------------------- ### Get Beginning of Minute for DateTime Source: https://guides.rubyonrails.org/v8.0/active_support_core_extensions.html Use `beginning_of_minute` to get a timestamp at the start of the current minute (hh:mm:00). This method is available for `DateTime` and `Time` objects. ```ruby date = DateTime.new(2010, 6, 7, 19, 55, 25) date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010 ``` -------------------------------- ### Install Action Text with Rails Command Source: https://guides.rubyonrails.org/v8.0/action_text_overview.html Installs Action Text and its JavaScript dependencies, adds image processing gem, creates necessary database migrations, and sets up default view partials. ```bash $ bin/rails action_text:install ``` -------------------------------- ### Get All Parent Modules with module_parents Source: https://guides.rubyonrails.org/v8.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`. ```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] ``` -------------------------------- ### Configure Bundler and Bootsnap in config/boot.rb Source: https://guides.rubyonrails.org/v8.0/initialization.html Sets up the Gemfile path and initializes Bundler and Bootsnap for dependency management and boot optimization. ```ruby ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. require "bootsnap/setup" # Speed up boot time by caching expensive operations. ``` -------------------------------- ### Initialize Rackup Server Source: https://guides.rubyonrails.org/v8.0/initialization.html The initialize method sets up server options, either from provided arguments or by parsing ARGV. ```ruby module Rackup class Server def initialize(options = nil) @ignore_options = [] if options @use_default_options = false @options = options @app = options[:app] if options[:app] else @use_default_options = true @options = parse_options(ARGV) end end end end ``` -------------------------------- ### Set Up Testing Database for Plugin Source: https://guides.rubyonrails.org/v8.0/plugins.html Navigates to the dummy Rails application within the plugin's test directory and creates the testing database using 'bin/rails db:create'. This ensures the plugin can be tested in a realistic Rails environment. ```bash cd test/dummy bin/rails db:create ``` -------------------------------- ### Define Basic Rails Routes Source: https://guides.rubyonrails.org/v8.0/getting_started.html Examples of mapping HTTP GET and POST requests to specific controller actions within the config/routes.rb file. ```ruby Rails.application.routes.draw do get "/products", to: "products#index" post "/products", to: "products#create" end ``` -------------------------------- ### Manual data setup for render Source: https://guides.rubyonrails.org/v8.0/layouts_and_rendering.html Manually populates instance variables and sets a flash message before rendering the index template to avoid a redirect 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 ``` -------------------------------- ### Pluck distinct column values Source: https://guides.rubyonrails.org/v8.0/active_record_querying.html Use `pluck` with `distinct` to retrieve an array of unique values from a specified column. This is useful for getting a list of all possible statuses, for example. ```ruby irb> Order.distinct.pluck(:status) SELECT DISTINCT status FROM orders => ["shipped", "being_packed", "cancelled"] ``` -------------------------------- ### Rake Command for Rails Gem Management Source: https://guides.rubyonrails.org/v8.0/2_2_release_notes.html Provides examples of Rake commands used for managing gem dependencies within a Rails application, including listing, installing, unpacking, and building gems and their dependencies. ```Shell rake gems rake gems:install rake gems:unpack rake gems:unpack:dependencies rake gems:build rake gems:refresh_specs ``` -------------------------------- ### Boot Application Source: https://guides.rubyonrails.org/v8.0/command_line.html Use `bin/rails boot` to boot the application and then exit. This can be useful for testing the application's startup process. ```bash bin/rails boot ``` -------------------------------- ### Create Database Migrations Source: https://guides.rubyonrails.org/v8.0/active_record_basics.html Provides an example of a database-agnostic migration file to create a new table with various column types. ```ruby class CreatePublications < ActiveRecord::Migration[8.0] def change create_table :publications do |t| t.string :title t.text :description t.references :publication_type t.references :publisher, polymorphic: true t.boolean :single_issue t.timestamps end end end ``` -------------------------------- ### Ruby on Rails: Active Model API Lint Testing Setup Source: https://guides.rubyonrails.org/v8.0/active_model_basics.html This example demonstrates how to set up lint tests for an Active Model object by including `ActiveModel::Lint::Tests` in a test case. It shows the basic structure for testing API compliance. ```ruby class Person include ActiveModel::API end ``` ```ruby require "test_helper" class PersonTest < ActiveSupport::TestCase include ActiveModel::Lint::Tests setup do @model = Person.new end end ``` -------------------------------- ### Initialize Rails Application Routes Source: https://guides.rubyonrails.org/v8.0/i18n.html Basic setup for a standard Rails application root route. ```ruby Rails.application.routes.draw do root to: "home#index" end ``` -------------------------------- ### Verify Ruby and Install Rails Source: https://guides.rubyonrails.org/v8.0/install_ruby_on_rails.html Verifies the current Ruby installation and installs the latest version of the Rails framework using the gem package manager. ```bash ruby --version gem install rails rails --version ``` -------------------------------- ### Start Rails Development Server Source: https://guides.rubyonrails.org/v8.0/getting_started.html This command boots the Puma web server within the application context. It ensures the correct version of Rails is used and provides a local URL to access the application. ```bash bin/rails server ``` -------------------------------- ### Connect via DATABASE_URL environment variable Source: https://guides.rubyonrails.org/v8.0/configuring.html Demonstrates connection behavior when config/database.yml is empty but DATABASE_URL is set. ```bash $ cat config/database.yml $ echo $DATABASE_URL postgresql://localhost/my_database ``` -------------------------------- ### Create a new Rails application Source: https://guides.rubyonrails.org/v8.0/command_line.html Initializes a new Rails project directory structure with default settings. ```bash $ rails new my_app create create README.md create Rakefile create config.ru create .gitignore create Gemfile create app ... create tmp/cache ... run bundle install ``` -------------------------------- ### Install and Update Bundler Source: https://guides.rubyonrails.org/v8.0/ruby_on_rails_guides_guidelines.html Commands to ensure the latest version of Bundler is installed or updated on the system. ```shell gem install bundler gem update bundler ``` -------------------------------- ### Install Action Text for Rich Text Fields (Rails CLI) Source: https://guides.rubyonrails.org/v8.0/getting_started.html These commands install Action Text, a Rails feature for handling rich text content with embeds. The process involves running the Action Text installer, installing bundle dependencies, and migrating the database to add necessary tables. Restarting the Rails server is required to load the new features. ```bash $ bin/rails action_text:install $ bundle install $ bin/rails db:migrate ``` -------------------------------- ### Install importmap-rails Gem Source: https://guides.rubyonrails.org/v8.0/working_with_javascript_in_rails.html Manually install the importmap-rails gem into an existing Rails application to manage JavaScript dependencies. ```bash $ bin/bundle add importmap-rails $ bin/rails importmap:install ``` -------------------------------- ### Customize Solid Cache Store Options Source: https://guides.rubyonrails.org/v8.0/caching_with_rails.html Example `config/cache.yml` showing how to customize Solid Cache store options like `max_age` and `max_size`. ```yaml default: store_options: # Cap age of oldest cache entry to fulfill retention policies max_age: <%= 60.days.to_i %> max_size: <%= 256.megabytes %> namespace: <%= Rails.env %> ``` -------------------------------- ### View Rails Server Output Source: https://guides.rubyonrails.org/v8.0/getting_started.html Example output from the Rails server startup process, indicating the server version, environment, and the local address where the application is listening. ```text => Booting Puma => Rails 8.0.0 application starting in development => Run `bin/rails server --help` for more startup options Puma starting in single mode... * Puma version: 6.4.3 (ruby 3.3.5-p100) ("The Eagle of Durango") * Min threads: 3 * Max threads: 3 * Environment: development * PID: 12345 * Listening on http://127.0.0.1:3000 * Listening on http://[::1]:3000 Use Ctrl-C to stop ``` -------------------------------- ### Connect via config/database.yml Source: https://guides.rubyonrails.org/v8.0/configuring.html Demonstrates connection behavior when config/database.yml is populated and DATABASE_URL is unset. ```bash $ cat config/database.yml development: adapter: postgresql database: my_database host: localhost $ echo $DATABASE_URL ``` -------------------------------- ### Verify Yarn Installation Source: https://guides.rubyonrails.org/v8.0/working_with_javascript_in_rails.html Verify that Yarn, a JavaScript package manager, is installed correctly and accessible in your system's PATH. ```bash $ yarn --version ``` -------------------------------- ### Verify Node.js Installation Source: https://guides.rubyonrails.org/v8.0/working_with_javascript_in_rails.html Verify that Node.js is installed correctly and meets the minimum version requirement for JavaScript bundling in Rails. ```bash $ node --version ``` -------------------------------- ### Verify Bun Installation Source: https://guides.rubyonrails.org/v8.0/working_with_javascript_in_rails.html Verify that the Bun JavaScript runtime and bundler is installed correctly and accessible in your system's PATH. ```bash $ bun --version ``` -------------------------------- ### Implement after_initialize and after_find Callbacks Source: https://guides.rubyonrails.org/v8.0/active_record_callbacks.html Shows how to hook into object instantiation and database retrieval events. ```ruby class User < ApplicationRecord after_initialize do |user| Rails.logger.info("You have initialized an object!") end after_find do |user| Rails.logger.info("You have found an object!") end end ``` ```ruby irb> User.new You have initialized an object! => # irb> User.first You have found an object! You have initialized an object! => # ``` -------------------------------- ### Parallel testing setup and teardown hooks Source: https://guides.rubyonrails.org/v8.0/testing.html Use parallelize_setup and parallelize_teardown to manage resources like databases when using process-based parallelization. ```ruby class ActiveSupport::TestCase parallelize_setup do |worker| # setup databases end parallelize_teardown do |worker| # cleanup databases end parallelize(workers: :number_of_processors) end ``` -------------------------------- ### Start Standalone Cable Server Source: https://guides.rubyonrails.org/v8.0/action_cable_overview.html Command to launch the standalone Action Cable server using Puma on a specific port. ```bash bundle exec puma -p 28080 cable/config.ru ``` -------------------------------- ### Calculate beginning and end of week Source: https://guides.rubyonrails.org/v8.0/active_support_core_extensions.html Returns the dates for the start and end of the week, with an optional argument to specify the starting day. ```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 ``` -------------------------------- ### Example Migration Output Source: https://guides.rubyonrails.org/v8.0/active_record_migrations.html Default output format for a migration creating a table and adding an index. ```text == CreateProducts: migrating ================================================= -- create_table(:products) -> 0.0028s == CreateProducts: migrated (0.0028s) ======================================== ``` -------------------------------- ### Vulnerable Token Validation Example Source: https://guides.rubyonrails.org/v8.0/security.html An example of code susceptible to SQL injection via parameter manipulation when deep_munge is not active. ```ruby unless params[:token].nil? user = User.find_by_token(params[:token]) user.reset_password! end ``` -------------------------------- ### Configure Solid Cache with SQLite Source: https://guides.rubyonrails.org/v8.0/caching_with_rails.html Example configuration for `config/database.yml` to set up a separate SQLite database for Solid Cache, using a default connection as a base. ```yaml production: primary: <<: *default database: storage/production.sqlite3 cache: <<: *default database: storage/production_cache.sqlite3 migrations_paths: db/cache_migrate ``` -------------------------------- ### Print Initializers Source: https://guides.rubyonrails.org/v8.0/command_line.html Use `bin/rails initializers` to list all defined initializers in the order they are invoked during application boot. ```bash bin/rails initializers ``` -------------------------------- ### Install Webpacker Gem Source: https://guides.rubyonrails.org/v8.0/upgrading_ruby_on_rails.html Webpacker is the default JavaScript compiler for Rails 6. If upgrading an existing app, include it in your Gemfile and install it. ```ruby gem "webpacker" ``` ```bash $ bin/rails webpacker:install ``` -------------------------------- ### Run EXPLAIN with eager loading (MySQL/MariaDB) Source: https://guides.rubyonrails.org/v8.0/active_record_querying.html When using eager loading (`includes`), `explain` may execute multiple queries. This example shows the output for MySQL and MariaDB. ```ruby Customer.where(id: 1).includes(:orders).explain ``` ```sql EXPLAIN SELECT `customers`.* FROM `customers` WHERE `customers`.`id` = 1 +----+-------------+-----------+-------+---------------+ | id | select_type | table | type | possible_keys | +----+-------------+-----------+-------+---------------+ | 1 | SIMPLE | customers | const | PRIMARY | +----+-------------+-----------+-------+---------------+ +---------+---------+-------+------+-------+ | key | key_len | ref | rows | Extra | +---------+---------+-------+------+-------+ | PRIMARY | 4 | const | 1 | | +---------+---------+-------+------+-------+ 1 row in set (0.00 sec) EXPLAIN SELECT `orders`.* FROM `orders` WHERE `orders`.`customer_id` IN (1) +----+-------------+--------+------+---------------+ | id | select_type | table | type | possible_keys | +----+-------------+--------+------+---------------+ | 1 | SIMPLE | orders | ALL | NULL | +----+-------------+--------+------+---------------+ +------+---------+------+------+-------------+ | key | key_len | ref | rows | Extra | +------+---------+------+------+-------------+ | NULL | NULL | NULL | 1 | Using where | +------+---------+------+------+-------------+ 1 row in set (0.00 sec) ``` -------------------------------- ### Install Migrations for Specific Database - Rails CLI Source: https://guides.rubyonrails.org/v8.0/engines.html Installs migrations targeting a specific database, useful in multi-database Rails applications. ```bash $ bin/rails railties:install:migrations DATABASE=animals ``` -------------------------------- ### Rails View Code Example Source: https://guides.rubyonrails.org/v8.0/command_line.html This is an example of a generated view file. It displays content and uses an instance variable set in the controller. ```erb

A Greeting for You!

<%= @message %>

``` -------------------------------- ### Puma Server Run Method Implementation Source: https://guides.rubyonrails.org/v8.0/initialization.html Handles the execution of the Puma server. It configures the server, sets up logging, creates a launcher instance, and starts the server, including graceful shutdown on interrupt. ```ruby module Rack module Handler module Puma # ... def self.run(app, options = {}) conf = self.config(app, options) log_writer = options.delete(:Silent) ? ::Puma::LogWriter.strings : ::Puma::LogWriter.stdio launcher = ::Puma::Launcher.new(conf, log_writer: log_writer, 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 ``` -------------------------------- ### Rails Controller Code Example Source: https://guides.rubyonrails.org/v8.0/command_line.html This is an example of a generated controller file. It defines an action and sets an instance variable to be used in the view. ```ruby class GreetingsController < ApplicationController def hello @message = "Hello, how are you today?" end end ``` -------------------------------- ### Create a book for an author manually Source: https://guides.rubyonrails.org/v8.0/association_basics.html Example of creating a record by explicitly setting the foreign key. ```ruby @book = Book.create(author_id: @author.id, published_at: Time.now) ``` -------------------------------- ### Integration Test GET Request Source: https://guides.rubyonrails.org/v8.0/4_2_release_notes.html Shows how to make a GET request in an integration test. The path must include a leading slash. ```ruby test "list all posts" do get "/posts" assert_response :success end ``` -------------------------------- ### Rails Test Runner Examples Source: https://guides.rubyonrails.org/v8.0/testing.html Illustrates various ways to run tests, including single tests by line number, line ranges, and multiple files/directories. ```bash Examples: You can run a single test by appending a line number to a filename: bin/rails test test/models/user_test.rb:27 You can run multiple tests with in a line range by appending the line range to a filename: bin/rails test test/models/user_test.rb:10-20 You can run multiple files and directories at the same time: bin/rails test test/controllers test/integration/login_test.rb By default test failures and errors are reported inline during a run. ``` -------------------------------- ### Install Migrations with Custom Path - Rails CLI Source: https://guides.rubyonrails.org/v8.0/engines.html Installs migrations from a specific engine, allowing for a custom path to store them within the application. ```bash $ bin/rails railties:install:migrations MIGRATIONS_PATH=db_blourgh ``` -------------------------------- ### Create New Rails Application Source: https://guides.rubyonrails.org/v8.0/3_0_release_notes.html Commands to initialize a new Rails application and navigate into the project directory. ```bash rails new myapp cd myapp ``` -------------------------------- ### Configure Solid Cache with PostgreSQL/MySQL Source: https://guides.rubyonrails.org/v8.0/caching_with_rails.html Example configuration for `config/database.yml` using a primary database connection as a base for the Solid Cache database, suitable for PostgreSQL or MySQL. ```yaml production: primary: &primary_production <<: *default database: app_production username: app password: <%= ENV["APP_DATABASE_PASSWORD"] %> cache: <<: *primary_production database: app_production_cache migrations_paths: db/cache_migrate ``` -------------------------------- ### Get Help for a Specific Rails Generator Source: https://guides.rubyonrails.org/v8.0/command_line.html You can get help for any generator by appending `--help` or `-h` to the command, similar to other Unix utilities. ```bash $ bin/rails generate controller --help Usage: bin/rails generate controller NAME [action action] [options] ... ... Description: ... To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'. ... Example: `bin/rails generate controller CreditCards open debit credit close` Credit card controller with URLs like /credit_cards/debit. Controller: app/controllers/credit_cards_controller.rb Test: test/controllers/credit_cards_controller_test.rb Views: app/views/credit_cards/debit.html.erb [...] Helper: app/helpers/credit_cards_helper.rb ``` -------------------------------- ### Define Rackup::Server#app Source: https://guides.rubyonrails.org/v8.0/initialization.html Determines how to build the application based on provided options, either from a string or a configuration file. ```ruby module Rackup class Server def app @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config end # ... private def build_app_and_options_from_config if !::File.exist? options[:config] abort "configuration #{options[:config]} not found" end Rack::Builder.parse_file(self.options[:config]) end def build_app_from_string Rack::Builder.new_from_string(self.options[:builder]) end end end ``` -------------------------------- ### Verify Rails Installation Version Source: https://guides.rubyonrails.org/v8.0/getting_started.html Checks the currently installed version of the Rails framework. This ensures the environment meets the minimum requirement of version 8.0.0. ```bash rails --version ``` -------------------------------- ### View help for rails new Source: https://guides.rubyonrails.org/v8.0/command_line.html Displays available options and configuration flags for the rails new command. ```bash $ rails new --help ``` -------------------------------- ### Validate and Configure Guides Source: https://guides.rubyonrails.org/v8.0/ruby_on_rails_guides_guidelines.html Commands to validate generated HTML for errors like duplicate IDs and to list available configuration environment variables. ```shell bundle exec rake guides:validate rake ``` -------------------------------- ### Install Rails Upgrade Plugin Source: https://guides.rubyonrails.org/v8.0/3_0_release_notes.html Installs the Rails Upgrade plugin via Git to assist in automating the upgrade process from older Rails versions. ```bash ruby script/plugin install git://github.com/rails/rails_upgrade.git ``` -------------------------------- ### Initialize Action Cable Consumer Source: https://guides.rubyonrails.org/v8.0/action_cable_overview.html Sets up the Action Cable consumer to manage WebSocket connections. It demonstrates default connection to /cable and custom URL configuration using strings or dynamic functions. ```javascript import { createConsumer } from "@rails/actioncable" export default createConsumer() // Custom URL examples createConsumer('wss://example.com/cable') createConsumer(getWebSocketURL) function getWebSocketURL() { const token = localStorage.get('auth-token') return `wss://example.com/cable?token=${token}` } ``` -------------------------------- ### Install All Railties Migrations - Rails CLI Source: https://guides.rubyonrails.org/v8.0/engines.html Copies migrations from all installed Railties (engines) into the application's `db/migrate` directory. Useful when managing multiple engines. ```bash $ bin/rails railties:install:migrations ``` -------------------------------- ### Create Channel Subscriptions Source: https://guides.rubyonrails.org/v8.0/action_cable_overview.html Demonstrates how a consumer subscribes to specific channels on the server. Multiple subscriptions can be created for different rooms or channels. ```javascript import consumer from "./consumer" // Single subscription consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }) // Multiple subscriptions consumer.subscriptions.create({ channel: "ChatChannel", room: "1st Room" }) consumer.subscriptions.create({ channel: "ChatChannel", room: "2nd Room" }) ```