### ClassMethods#setup Source: https://api.rubyonrails.org/classes/ActiveSupport/Testing/SetupAndTeardown/ClassMethods.html Adds a callback that runs before the TestCase#setup method. ```APIDOC ## ClassMethods#setup ### Description Add a callback, which runs before `TestCase#setup`. ### Method `setup(*args, &block)` ### Parameters - `*args`: Arguments to pass to the callback. - `&block`: A block to be executed as the callback. ### Request Example ```ruby setup do # setup code end ``` ### Response This method does not return a value; it registers a callback. ``` -------------------------------- ### Install Rails Source: https://api.rubyonrails.org/ Use the gem command to install the Rails framework. ```bash $ gem install rails ``` -------------------------------- ### Define Setup Callback in Rails Source: https://api.rubyonrails.org/classes/ActiveSupport/Testing/SetupAndTeardown/ClassMethods.html Use this method to add a callback that runs before `TestCase#setup`. It accepts arguments and a block for defining the setup logic. ```ruby # File activesupport/lib/active_support/testing/setup_and_teardown.rb, line 29 def setup(*args, &block) set_callback(:setup, :before, *args, &block) end ``` -------------------------------- ### Simple Token Authentication Example Source: https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html This example demonstrates a basic setup for token authentication in a Rails controller. It uses `before_action` to authenticate requests and `authenticate_or_request_with_http_token` to handle token verification. ```ruby class PostsController < ApplicationController TOKEN = "secret" before_action :authenticate, except: [ :index ] def index render plain: "Everyone can see me!" end def edit render plain: "I'm only accessible if you know the password" end private def authenticate authenticate_or_request_with_http_token do |token, options| # Compare the tokens in a time-constant manner, to mitigate # timing attacks. ActiveSupport::SecurityUtils.secure_compare(token, TOKEN) end end end ``` -------------------------------- ### Basic `driven_by` Configuration Examples Source: https://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html These examples show various ways to configure the driver for system tests using the `driven_by` method. ```ruby driven_by :cuprite ``` ```ruby driven_by :selenium, screen_size: [800, 800] ``` ```ruby driven_by :selenium, using: :chrome ``` ```ruby driven_by :selenium, using: :headless_chrome ``` ```ruby driven_by :selenium, using: :firefox ``` ```ruby driven_by :selenium, using: :headless_firefox ``` -------------------------------- ### Start DBConsole Class Method Source: https://api.rubyonrails.org/classes/Rails/DBConsole.html Entry point for starting the database console command. ```ruby # File railties/lib/rails/commands/dbconsole/dbconsole_command.rb, line 8 def self.start(*args) new(*args).start end ``` -------------------------------- ### Start server Source: https://api.rubyonrails.org/classes/Rails/Server.html Starts the server process, sets up signal traps, and executes lifecycle callbacks. ```ruby # File railties/lib/rails/commands/server/server_command.rb, line 32 def start(after_stop_callback = nil) trap(:INT) { exit } create_tmp_directories setup_dev_caching log_to_stdout if options[:log_stdout] super() ensure after_stop_callback.call if after_stop_callback end ``` -------------------------------- ### Test a Log Subscriber Source: https://api.rubyonrails.org/classes/ActiveSupport/LogSubscriber/TestHelper.html Example of testing a log subscriber by including the helper and attaching the subscriber in the setup block. ```ruby class SyncLogSubscriberTest < ActiveSupport::TestCase include ActiveSupport::LogSubscriber::TestHelper setup do ActiveRecord::LogSubscriber.attach_to(:active_record) end def test_basic_query_logging Developer.all.to_a wait assert_equal 1, @logger.logged(:debug).size assert_match(/Developer Load/, @logger.logged(:debug).last) assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last) end end ``` -------------------------------- ### Rails::Console::IRBConsole#start Source: https://api.rubyonrails.org/classes/Rails/Console/IRBConsole.html Starts the interactive Ruby console session. ```APIDOC ## Rails::Console::IRBConsole#start ### Description Starts the interactive Ruby console session, configuring prompts and backtrace filters. ### Method `start()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Install Action View with RubyGems Source: https://api.rubyonrails.org/classes/ActionView.html Use this command to install the latest version of Action View. Ensure you have RubyGems installed. ```bash $ gem install actionview ``` -------------------------------- ### Rails::Generators::TestCase with Setup Callback Source: https://api.rubyonrails.org/classes/Rails/Generators/TestCase.html This snippet shows how to use the `setup` callback to ensure the destination is clean before running each test. ```APIDOC ## Rails::Generators::TestCase with Setup Callback ### Description If you want to ensure your destination root is clean before running each test, you can set a setup callback. ### Method N/A (Class Definition) ### Endpoint N/A (Class Definition) ### Parameters N/A (Class Definition) ### Request Example ```ruby class AppGeneratorTest < Rails::Generators::TestCase tests AppGenerator destination File.expand_path("../tmp", __dir__) setup :prepare_destination end ``` ### Response N/A (Class Definition) ### Response Example N/A (Class Definition) ``` -------------------------------- ### Custom App Builder Example Source: https://api.rubyonrails.org/classes/Rails/AppBuilder.html Example of a custom app builder that adds 'rspec-rails' gem and runs bundle install and rspec install. ```ruby class CustomAppBuilder < Rails::AppBuilder def test @generator.gem "rspec-rails", group: [:development, :test] run "bundle install" generate "rspec:install" end end ``` -------------------------------- ### Initialize ActionView::Template::Sources::File Source: https://api.rubyonrails.org/classes/ActionView/Template/Sources/File.html Creates a new instance by specifying the path to the template file. ```ruby # File actionview/lib/action_view/template/sources/file.rb, line 7 def initialize(filename) @filename = filename end ``` -------------------------------- ### Get Event Start Time Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the start time of the event in seconds. Returns nil if the event has not started. ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 124 def time @time / 1000.0 if @time end ``` -------------------------------- ### Start the Rails Server Source: https://api.rubyonrails.org/ Navigate to the project directory and launch the local development server. ```bash $ cd myapp $ bin/rails server ``` -------------------------------- ### Get start of hour Source: https://api.rubyonrails.org/classes/DateTime.html Returns a new DateTime representing the start of the hour (hh:00:00). ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 146 def beginning_of_hour change(min: 0) end ``` -------------------------------- ### Initialize a new preview instance Source: https://api.rubyonrails.org/classes/ActionMailer/Preview.html Sets up a new instance of the preview class with optional parameters. ```ruby def initialize(params = {}) @params = params end ``` -------------------------------- ### Get start of day Source: https://api.rubyonrails.org/classes/DateTime.html Returns a new DateTime representing the start of the day (0:00). ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 122 def beginning_of_day change(hour: 0) end ``` -------------------------------- ### ActiveModel Installation Source: https://api.rubyonrails.org/classes/ActiveModel.html Instructions on how to install the latest version of ActiveModel using RubyGems. ```APIDOC ## Download and installation The latest version of Active `Model` can be installed with RubyGems: ```bash $ gem install activemodel ``` Source code can be downloaded as part of the Rails project on GitHub * github.com/rails/rails/tree/main/activemodel ``` -------------------------------- ### Get start of minute Source: https://api.rubyonrails.org/classes/DateTime.html Returns a new DateTime representing the start of the minute (hh:mm:00). ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 158 def beginning_of_minute change(sec: 0) end ``` -------------------------------- ### Start DBConsole Instance Method Source: https://api.rubyonrails.org/classes/Rails/DBConsole.html Executes the database console command using the configured adapter. ```ruby # File railties/lib/rails/commands/dbconsole/dbconsole_command.rb, line 17 def start adapter_class.dbconsole(db_config, @options) rescue NotImplementedError, ActiveRecord::AdapterNotFound, LoadError => error abort error.message end ``` -------------------------------- ### Get Next Quarter Date Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `next_quarter` as a shorthand for `months_since(3)` to get the date three months in the future. No special setup is required. ```ruby def next_quarter months_since(3) end ``` -------------------------------- ### Full-Stack Broadcasting Example Source: https://api.rubyonrails.org/classes/ActionCable/Server/Broadcasting.html Illustrates how to set up a channel to receive broadcasts and how to send broadcasts from the server. Client-side JavaScript is also shown for receiving notifications. ```ruby class WebNotificationsChannel < ApplicationCable::Channel def subscribed stream_from "web_notifications_#{current_user.id}" end end # Somewhere in your app this is called, perhaps from a NewCommentJob: ActionCable.server.broadcast \ "web_notifications_1", { title: "New things!", body: "All that's fit for print" } # Client-side JavaScript, which assumes you've already requested the right to send web notifications: App.cable.subscriptions.create("WebNotificationsChannel", { received: function(data) { new Notification(data['title'], { body: data['body'] }) } }) ``` -------------------------------- ### Setup Test Controller and Request Source: https://api.rubyonrails.org/classes/ActionView/TestCase/Behavior.html The `setup_with_controller` method initializes a test controller, request, view flow, and output buffer. It also defines a `_test_case` method on the controller to link it back to the test instance. ```ruby # File actionview/lib/action_view/test_case.rb, line 269 def setup_with_controller controller_class = Class.new(ActionView::TestCase::TestController) @controller = controller_class.new @request = @controller.request @view_flow = ActionView::OutputFlow.new @output_buffer = ActionView::OutputBuffer.new @rendered = self.class.content_class.new(+"") test_case_instance = self controller_class.define_method(:_test_case) { test_case_instance } end ``` -------------------------------- ### Get Date from Last Year Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `last_year` as a shorthand for `years_ago(1)` to get the date one year prior. No special setup is required. ```ruby def last_year years_ago(1) end ``` -------------------------------- ### Get Date from Last Month Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `last_month` as a shorthand for `months_ago(1)` to get the date one month prior. No special setup is required. ```ruby def last_month months_ago(1) end ``` -------------------------------- ### Module ActiveSupport::Testing::SetupAndTeardown Source: https://api.rubyonrails.org/classes/ActiveSupport/Testing/SetupAndTeardown.html Provides methods to define setup and teardown callbacks within a TestCase class. ```APIDOC ## Module ActiveSupport::Testing::SetupAndTeardown ### Description Adds support for `setup` and `teardown` callbacks. These callbacks serve as a replacement to overwriting the setup and teardown methods of your `TestCase`. ### Methods - **prepended(klass)**: Initializes the class by including ActiveSupport::Callbacks, defining setup and teardown callbacks, and extending ClassMethods. ### Usage Example ```ruby class ExampleTest < ActiveSupport::TestCase setup do # ... end teardown do # ... end end ``` ``` -------------------------------- ### Get beginning of month Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Returns a new date/time at the start of the month. ```ruby today = Date.today # => Thu, 18 Jun 2015 today.beginning_of_month # => Mon, 01 Jun 2015 ``` ```ruby now = DateTime.current # => Thu, 18 Jun 2015 15:23:13 +0000 now.beginning_of_month # => Mon, 01 Jun 2015 00:00:00 +0000 ``` ```ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 125 def beginning_of_month first_hour(change(day: 1)) end ``` -------------------------------- ### Start Console with Environment and Sandbox Source: https://api.rubyonrails.org/classes/Rails/Console.html Starts the Rails console session. It sets the environment if specified and provides user feedback on whether sandbox mode is active. ```ruby def start set_environment! if environment? if sandbox? puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" puts "Any modifications you make will be rolled back on exit" else puts "Loading #{Rails.env} environment (Rails #{Rails.version})" end console.start end ``` -------------------------------- ### Get Monday of the Week Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `monday` to get the date of Monday for the current week, assuming the week starts on Monday. For `DateTime` objects, the time is set to 0:00. ```ruby def monday beginning_of_week(:monday) end ``` -------------------------------- ### Get beginning of hour Source: https://api.rubyonrails.org/classes/Time.html Returns a new Time representing the start of the hour (x:00). ```ruby # File activesupport/lib/active_support/core_ext/time/calculations.rb, line 260 def beginning_of_hour change(min: 0) end ``` -------------------------------- ### Configure resource modules and paths Source: https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html Examples of setting controller modules and custom paths for resources. ```ruby # routes call Admin::PostsController resources :posts, module: "admin" # resource actions are at /admin/posts. resources :posts, path: "admin/posts" ``` -------------------------------- ### Initialize Rails::Server Source: https://api.rubyonrails.org/classes/Rails/Server.html Initializes a new server instance with optional configuration. ```ruby # File railties/lib/rails/commands/server/server_command.rb, line 18 def initialize(options = nil) @default_options = options || {} super(@default_options) set_environment end ``` -------------------------------- ### Get beginning of day Source: https://api.rubyonrails.org/classes/Time.html Returns a new Time representing the start of the day (0:00). ```ruby # File activesupport/lib/active_support/core_ext/time/calculations.rb, line 231 def beginning_of_day change(hour: 0) end ``` -------------------------------- ### Get beginning of minute Source: https://api.rubyonrails.org/classes/Time.html Returns a new Time representing the start of the minute (x:xx:00). ```ruby # File activesupport/lib/active_support/core_ext/time/calculations.rb, line 276 def beginning_of_minute change(sec: 0) end ``` -------------------------------- ### Prepare all databases Source: https://api.rubyonrails.org/classes/ActiveRecord/Tasks/DatabaseTasks.html Initializes and migrates all databases defined in the current environment configuration. ```ruby # File activerecord/lib/active_record/tasks/database_tasks.rb, line 174 def prepare_all seed = false dump_db_configs = [] each_current_configuration(env) do |db_config| database_initialized = initialize_database(db_config) seed = true if database_initialized && db_config.seeds? end each_current_environment(env) do |environment| db_configs_with_versions(environment).sort.each do |version, db_configs| dump_db_configs |= db_configs db_configs.each do |db_config| with_temporary_pool(db_config) do migrate(version) end end end end # Dump schema for databases that were migrated. if ActiveRecord.dump_schema_after_migration dump_db_configs.each do |db_config| with_temporary_pool(db_config) do dump_schema(db_config) end end end load_seed if seed end ``` -------------------------------- ### Get Sunday of the week Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Returns the Sunday of the current week, assuming the week starts on Monday. ```ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 290 def sunday end_of_week(:monday) end ``` -------------------------------- ### Get Event Allocations Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the number of allocations made between the call to `start!` and the call to `finish!`. ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 176 def allocations @allocation_count_finish - @allocation_count_start end ``` -------------------------------- ### Get range for the whole week Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Returns a Range representing the full week, starting on the specified day. ```ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 316 def all_week(start_day = Date.beginning_of_week) beginning_of_week(start_day)..end_of_week(start_day) end ``` -------------------------------- ### Constructor: new Source: https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations/HashConfig.html Initializes a new HashConfig object with environment, name, and configuration details. ```APIDOC ## new(env_name, name, configuration_hash) ### Description Initializes a new HashConfig object. This object stores the database configuration settings provided in a hash. ### Parameters - **env_name** (String) - Required - The Rails environment (e.g., "development"). - **name** (String) - Required - The database configuration name (e.g., "primary"). - **configuration_hash** (Hash) - Required - The hash containing database adapter, name, and connection information. ``` -------------------------------- ### Rails::Server Initialization and Lifecycle Source: https://api.rubyonrails.org/classes/Rails/Server.html Methods for initializing the server, configuring the environment, and starting the server process. ```APIDOC ## new(options) ### Description Initializes a new instance of the Rails::Server with optional configuration settings. ### Parameters #### Request Body - **options** (Hash) - Optional - A hash of configuration options for the server. ## set_environment() ### Description Sets the RAILS_ENV environment variable based on the provided server options. ## start(after_stop_callback) ### Description Starts the Rails server, sets up necessary directories, caching, and logging, and executes an optional callback after the server stops. ### Parameters #### Request Body - **after_stop_callback** (Proc) - Optional - A callback function to execute after the server process terminates. ``` -------------------------------- ### Get Date in Next Week Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `next_week` to get a date in the following week. It defaults to the beginning of the week and can optionally preserve the time if `same_time` is true. Examples show default and specific day usage. ```ruby def next_week(given_day_in_next_week = Date.beginning_of_week, same_time: false) result = first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week))) same_time ? copy_time_to(result) : result end ``` -------------------------------- ### Establish Database Connections Source: https://api.rubyonrails.org/files/activerecord/README_rdoc.html Configure database adapters and connection parameters. ```ruby # connect to SQLite3 ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3') # connect to MySQL with authentication ActiveRecord::Base.establish_connection( adapter: 'mysql2', host: 'localhost', username: 'me', password: 'secret', database: 'activerecord' ) ``` -------------------------------- ### ActionCable::Server::Configuration#initialize Source: https://api.rubyonrails.org/classes/ActionCable/Server/Configuration.html Initializes the Action Cable server configuration with default values. ```APIDOC ## ActionCable::Server::Configuration#initialize ### Description Initializes the Action Cable server configuration with default values. ### Method `initialize` ### Endpoint N/A (Constructor) ### Parameters None ### Request Example ```ruby ActionCable::Server::Configuration.new ``` ### Response #### Success Response (200) Initializes a new Configuration object with default settings. #### Response Example (No direct response, object is initialized in memory) ``` -------------------------------- ### Get Beginning of Week Source: https://api.rubyonrails.org/classes/Date.html Retrieves the configured start of the week for the current request. Defaults to :monday if not explicitly set. ```ruby # File activesupport/lib/active_support/core_ext/date/calculations.rb, line 19 def beginning_of_week ::ActiveSupport::IsolatedExecutionState[:beginning_of_week] || beginning_of_week_default || :monday end ``` -------------------------------- ### Example URL Configuration Source: https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations/UrlConfig.html A database configuration entry can be provided as a URL string. ```plaintext postgres://localhost/foo ``` -------------------------------- ### Get Event GC Time Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the time spent in GC in milliseconds between the call to `start!` and the call to `finish!`. ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 182 def gc_time (@gc_time_finish - @gc_time_start) / 1_000_000.0 end ``` -------------------------------- ### Get Event CPU Time Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the CPU time in milliseconds passed between the call to `start!` and the call to `finish!`. ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 163 def cpu_time @cpu_time_finish - @cpu_time_start end ``` -------------------------------- ### Initialize MemCacheStore Source: https://api.rubyonrails.org/classes/ActiveSupport/Cache/MemCacheStore.html Create a new MemCacheStore instance by providing server addresses or relying on environment variables. ```ruby ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229") ``` ```ruby # File activesupport/lib/active_support/cache/mem_cache_store.rb, line 76 def initialize(*addresses) addresses = addresses.flatten options = addresses.extract_options! if options.key?(:cache_nils) options[:skip_nil] = !options.delete(:cache_nils) end options[:max_key_size] ||= MAX_KEY_SIZE super(options) unless [String, Dalli::Client, NilClass].include?(addresses.first.class) raise ArgumentError, "First argument must be an empty array, address, or array of addresses." end @mem_cache_options = options.dup # The value "compress: false" prevents duplicate compression within Dalli. @mem_cache_options[:compress] = false (OVERRIDDEN_OPTIONS - %i(compress)).each { |name| @mem_cache_options.delete(name) } # Set the default serializer for Dalli to prevent warning about # inheriting the default serializer. @mem_cache_options[:serializer] = Marshal @data = self.class.build_mem_cache(*(addresses + [@mem_cache_options])) end ``` -------------------------------- ### Setup Controller Request and Response Source: https://api.rubyonrails.org/classes/ActionController/TestCase/Behavior.html Initializes the controller, request, and response objects for a test case. ```ruby # File actionpack/lib/action_controller/test_case.rb, line 564 def setup_controller_request_and_response @controller = nil unless defined? @controller @response_klass = ActionDispatch::TestResponse if klass = self.class.controller_class if klass < ActionController::Live @response_klass = LiveTestResponse end unless @controller begin @controller = klass.new rescue warn "could not construct controller #{klass}" if $VERBOSE end end end @request = TestRequest.create(@controller.class) @response = build_response @response_klass @response.request = @request if @controller @controller.request = @request @controller.params = {} end end ``` -------------------------------- ### Get Beginning of Week - Ruby Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Returns a new date/time representing the start of this week on the given day. Week is assumed to start on `start_day`, default is `Date.beginning_of_week` or `config.beginning_of_week` when set. `DateTime` objects have their time set to 0:00. ```ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 267 def beginning_of_week(start_day = Date.beginning_of_week) result = days_ago(days_to_week_start(start_day)) acts_like?(:time) ? result.midnight : result end ``` -------------------------------- ### Get Beginning of Quarter - Ruby Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Returns a new date/time at the start of the quarter. For DateTime objects, the time is set to 0:00. ```ruby today = Date.today # => Fri, 10 Jul 2015 today.beginning_of_quarter # => Wed, 01 Jul 2015 ``` ```ruby now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 now.beginning_of_quarter # => Wed, 01 Jul 2015 00:00:00 +0000 ``` -------------------------------- ### Import and Start Active Storage from npm Source: https://api.rubyonrails.org/classes/ActiveStorage.html Import the Active Storage library from the npm package and call `ActiveStorage.start()` to initialize it. This is suitable for projects using npm for dependency management. ```javascript import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start() ``` -------------------------------- ### Get Column for Attribute Example in Rails Source: https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html Illustrates how `column_for_attribute` works, showing results for an existing attribute and a non-existent one. ```ruby class Person < ActiveRecord::Base end person = Person.new person.column_for_attribute(:name) # the result depends on the ConnectionAdapter # => # person.column_for_attribute(:nothing) # => #, ...> ``` -------------------------------- ### new Source: https://api.rubyonrails.org/classes/Rails/Engine/Configuration.html Initializes a new Engine Configuration. ```APIDOC ## Class Public methods ### new(root = nil) Initializes a new configuration with an optional root directory. #### Parameters - **root** (String) - Optional. The root path for the engine configuration. #### Source ```ruby # File railties/lib/rails/engine/configuration.rb, line 41 def initialize(root = nil) super() @root = root @generators = app_generators.dup @middleware = Rails::Configuration::MiddlewareStackProxy.new @javascript_path = "javascript" @route_set_class = ActionDispatch::Routing::RouteSet @default_scope = nil @autoload_paths = [] @autoload_once_paths = [] @eager_load_paths = [] end ``` ``` -------------------------------- ### ActionController::Renderer Initialization Source: https://api.rubyonrails.org/classes/ActionController/Renderer.html Demonstrates how to get and initialize a renderer instance. ```APIDOC ## GET /renderer/initialize ### Description Obtain a renderer instance from a controller class. ### Method GET ### Endpoint `ApplicationController.renderer` or `PostsController.renderer` ### Parameters None ### Request Example ```ruby ApplicationController.renderer ``` ### Response An instance of `ActionController::Renderer`. #### Success Response (200) - **renderer_instance** (ActionController::Renderer) - The renderer object. #### Response Example ```ruby # ``` ``` ```APIDOC ## POST /renderer/initialize/new ### Description Initializes a new `Renderer` instance with specific environment options. ### Method POST ### Endpoint `ApplicationController.renderer.new(env = nil)` ### Parameters #### Request Body - **env** (Hash) - Optional. The Rack env to use for mocking a request. Can include keys like `:http_host`, `:https`, `:method`, `:script_name`, `:input`. ### Request Example ```json { "env": { "method": "post", "http_host": "example.com" } } ``` ### Response A new `ActionController::Renderer` instance. #### Success Response (200) - **renderer_instance** (ActionController::Renderer) - The new renderer object. #### Response Example ```ruby # ``` ``` ```APIDOC ## POST /renderer/initialize/with_defaults ### Description Creates a new renderer instance with merged default values. ### Method POST ### Endpoint `renderer_instance.with_defaults(defaults)` ### Parameters #### Request Body - **defaults** (Hash) - Default values for the Rack env. Entries are specified in the same format as `env` in `::new`. ### Request Example ```json { "defaults": { "script_name": "/app" } } ``` ### Response A new `ActionController::Renderer` instance with updated defaults. #### Success Response (200) - **renderer_instance** (ActionController::Renderer) - The new renderer object. #### Response Example ```ruby # ``` ``` -------------------------------- ### Get Array Tail from Position Source: https://api.rubyonrails.org/classes/Array.html Returns the tail of the array starting from the specified position. Handles positive, negative, and out-of-bounds positions. ```ruby %w( a b c d ).from(0) # => ["a", "b", "c", "d"] ``` ```ruby %w( a b c d ).from(2) # => ["c", "d"] ``` ```ruby %w( a b c d ).from(10) # => [] ``` ```ruby %w().from(0) # => [] ``` ```ruby %w( a b c d ).from(-2) # => ["c", "d"] ``` ```ruby %w( a b c ).from(-10) # => [] ``` ```ruby def from(position) self[position, length] || [] end ``` -------------------------------- ### Calculate Event Duration Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the difference in milliseconds between when the execution of the event started and when it ended. This example demonstrates how to subscribe to an event and measure its duration. ```ruby ActiveSupport::Notifications.subscribe('wait') do |event| @event = event end ActiveSupport::Notifications.instrument('wait') do sleep 1 end @event.duration # => 1000.138 ``` ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 198 def duration @end - @time end ``` -------------------------------- ### ActionCable::Server::Broadcasting::Broadcaster#initialize Source: https://api.rubyonrails.org/classes/ActionCable/Server/Broadcasting/Broadcaster.html Initializes a new Broadcaster instance. ```APIDOC ## initialize(server, broadcasting, coder:) ### Description Initializes a new Broadcaster instance with the given server, broadcasting channel, and coder. ### Method `initialize` ### Parameters - **server** (Object) - Required - The Action Cable server instance. - **broadcasting** (String) - Required - The name of the channel to broadcast to. - **coder** (Object) - Optional - The coder object to encode messages. ``` -------------------------------- ### Get Video Metadata - ActiveStorage::Analyzer::VideoAnalyzer Source: https://api.rubyonrails.org/classes/ActiveStorage/Analyzer/VideoAnalyzer.html Use this to extract metadata from a video blob. Ensure FFmpeg is installed as it's a dependency. ```ruby ActiveStorage::Analyzer::VideoAnalyzer.new(blob).metadata # => { width: 640.0, height: 480.0, duration: 5.0, angle: 0, display_aspect_ratio: [4, 3], audio: true, video: true } ``` -------------------------------- ### Establish Database Connection Source: https://api.rubyonrails.org/classes/ActiveRecord.html Connect to a database using `establish_connection`, specifying the adapter and database details. This example shows connecting to an SQLite3 database. ```ruby # connect to SQLite3 ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3') ``` -------------------------------- ### Prepare Callbacks Source: https://api.rubyonrails.org/classes/Rails/Railtie/Configuration.html Manages generic callbacks to run before initialization. ```ruby # File railties/lib/rails/railtie/configuration.rb, line 86 def to_prepare(&blk) to_prepare_blocks << blk if blk end ``` ```ruby # File railties/lib/rails/railtie/configuration.rb, line 80 def to_prepare_blocks @@to_prepare_blocks ||= [] end ``` -------------------------------- ### Get Rails Version Source: https://api.rubyonrails.org/classes/Rails/API/EdgeTask.html Returns the current Rails version as 'main' followed by the short Git commit hash. Requires Git to be installed and accessible. ```ruby def rails_version "main@#{`git rev-parse HEAD`[0, 7]}" end ``` -------------------------------- ### Constructor: new Source: https://api.rubyonrails.org/classes/ActionView/TemplateDetails/Requested.html Initializes a new instance of Requested with specific template details and builds index hashes for lookup. ```APIDOC ## Class Method: new ### Description Initializes a new instance of ActionView::TemplateDetails::Requested. It sets the locale, handlers, formats, and variants, and builds internal index hashes for efficient lookup. ### Parameters - **locale** (Symbol/String) - Required - The locale for the template. - **handlers** (Array) - Required - The template handlers (e.g., erb, builder). - **formats** (Array) - Required - The requested formats (e.g., html, json). - **variants** (Array/:any) - Required - The requested variants or :any for all variants. ### Request Example ```ruby ActionView::TemplateDetails::Requested.new( locale: :en, handlers: [:erb, :builder], formats: [:html], variants: :any ) ``` ``` -------------------------------- ### Example Usage of Audio Analyzer Source: https://api.rubyonrails.org/classes/ActiveStorage/Analyzer/AudioAnalyzer.html Demonstrates how to use the ActiveStorage::Analyzer::AudioAnalyzer to get metadata from a blob. This analyzer requires the FFmpeg system library. ```ruby ActiveStorage::Analyzer::AudioAnalyzer.new(blob).metadata # => { duration: 5.0, bit_rate: 320340, sample_rate: 44100, tags: { encoder: "Lavc57.64", ... } } ``` -------------------------------- ### Initialize Database Configurations Source: https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations.html Initializes a new instance of DatabaseConfigurations with provided configurations. ```ruby def initialize(configurations = {}) @configurations = build_configs(configurations) end ``` -------------------------------- ### Use fresh_when for conditional GET requests Source: https://api.rubyonrails.org/classes/ActionController/ConditionalGet.html Examples of using fresh_when to handle ETags and last-modified headers for single records, collections, and custom templates. ```ruby def show @article = Article.find(params[:id]) fresh_when(etag: @article, last_modified: @article.updated_at, public: true) end ``` ```ruby def show @article = Article.find(params[:id]) fresh_when(@article) end ``` ```ruby def index @articles = Article.all fresh_when(@articles) end ``` ```ruby def show @article = Article.find(params[:id]) fresh_when(@article, public: true, cache_control: { no_cache: true }) end ``` ```ruby before_action { fresh_when @article, template: "widgets/show" } ``` -------------------------------- ### Class Method: new Source: https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations.html Initializes a new instance of ActiveRecord::DatabaseConfigurations. ```APIDOC ## Class Public methods ### **new**(configurations = {}) Link Source: show | on GitHub ```ruby # File activerecord/lib/active_record/database_configurations.rb, line 75 def initialize(configurations = {}) @configurations = build_configs(configurations) end ``` ``` -------------------------------- ### Get Next Occurrence of a Day of Week Source: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html Use `next_occurring(day_of_week)` to find the next date/time for a specified day of the week. Example usage provided for clarity. ```ruby def next_occurring(day_of_week) from_now = DAYS_INTO_WEEK.fetch(day_of_week) - wday from_now += 7 unless from_now > 0 advance(days: from_now) end ``` -------------------------------- ### Get All Attachments Reflections in Rails Source: https://api.rubyonrails.org/classes/ActiveStorage/Reflection/ActiveRecordExtensions/ClassMethods.html Returns an array of reflection objects for all attachments associated with a class. No specific setup is required beyond having Active Storage configured. ```ruby def reflect_on_all_attachments attachment_reflections.values end ``` -------------------------------- ### Initialize MemCacheStore Source: https://api.rubyonrails.org/classes/ActiveSupport/Cache/MemCacheStore.html Creates a new instance of the MemCacheStore, connecting to specified Memcached server addresses. ```APIDOC ## Constructor: new(*addresses) ### Description Creates a new MemCacheStore object. If no addresses are provided, it defaults to ENV['MEMCACHE_SERVERS'] or localhost:11211. ### Parameters #### Path Parameters - **addresses** (String/Array) - Optional - Host names or host:port strings. ``` -------------------------------- ### Example Usage of DatabaseTasks Outside Rails Source: https://api.rubyonrails.org/classes/ActiveRecord/Tasks/DatabaseTasks.html Demonstrates how to configure and use DatabaseTasks for database operations when not running within a Rails application. Requires manual setup of configuration values. ```ruby include ActiveRecord::Tasks DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml') DatabaseTasks.db_dir = 'db' # other settings... DatabaseTasks.create_current('production') ``` -------------------------------- ### Controller Inheritance and Layout Assignment Examples Source: https://api.rubyonrails.org/classes/ActionView/Layouts.html Provides examples of controller inheritance and how layout assignments are resolved. Demonstrates explicit layout setting, dynamic layout selection, and disabling layouts. ```ruby class BankController < ActionController::Base # bank.html.erb exists class ExchangeController < BankController # exchange.html.erb exists class CurrencyController < BankController class InformationController < BankController layout "information" class TellerController < InformationController # teller.html.erb exists class EmployeeController < InformationController # employee.html.erb exists layout nil class VaultController < BankController layout :access_level_layout class TillController < BankController layout false ``` -------------------------------- ### FileSystemResolver Initialization Source: https://api.rubyonrails.org/classes/ActionView/FileSystemResolver.html Initializes a new FileSystemResolver instance with a specified path. ```APIDOC ## new(path) ### Description Creates a new instance of FileSystemResolver. It expands the provided path and initializes internal caches. ### Parameters - **path** (String) - Required - The filesystem path to resolve templates from. ``` -------------------------------- ### Get Action View Gem Version Source: https://api.rubyonrails.org/classes/ActionView.html Retrieves the currently installed version of Action View as a Gem::Version object. This is useful for dependency checks or displaying version information. ```ruby # File actionview/lib/action_view/gem_version.rb, line 5 def self.gem_version Gem::Version.new VERSION::STRING end ``` -------------------------------- ### Get Event Idle Time Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Event.html Returns the idle time in milliseconds passed between the call to `start!` and the call to `finish!`. Idle time is calculated as total duration minus CPU time. ```ruby # File activesupport/lib/active_support/notifications/instrumenter.rb, line 169 def idle_time diff = duration - cpu_time diff > 0.0 ? diff : 0.0 end ``` -------------------------------- ### boot_application! Source: https://api.rubyonrails.org/classes/Rails/Command/Actions.html Boots the Rails application by requiring the application and setting up the environment if necessary. ```APIDOC ## boot_application! ### Description Boots the Rails application by requiring the application and setting up the environment if necessary. ### Method Instance Public method ### Endpoint N/A (Internal method) ### Parameters None ### Request Example None ### Response None ### Source File railties/lib/rails/command/actions.rb, line 18 ``` -------------------------------- ### Define Comment Model with after_create Callback Source: https://api.rubyonrails.org/classes/ActiveRecord/Suppressor.html This example shows a typical ActiveRecord model setup where a notification is created after a comment is saved. Use this pattern when you want to trigger actions upon record creation. ```ruby class Comment < ActiveRecord::Base belongs_to :commentable, polymorphic: true after_create -> { Notification.create! comment: self, recipients: commentable.recipients } end ``` -------------------------------- ### Example System Test for User Creation Source: https://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html This is a basic example of a system test that navigates to a users path, clicks a button, fills in a form, submits it, and asserts that the text is present. ```ruby require "application_system_test_case" class Users::CreateTest < ApplicationSystemTestCase test "adding a new user" do visit users_path click_on 'New User' fill_in 'Name', with: 'Arya' click_on 'Create User' assert_text 'Arya' end end ``` -------------------------------- ### Boot the Rails application Source: https://api.rubyonrails.org/classes/Rails/Command/Actions.html Initializes the application environment if the APP_PATH constant is defined. ```ruby # File railties/lib/rails/command/actions.rb, line 18 def boot_application! require_application! Rails.application.require_environment! if defined?(APP_PATH) end ``` -------------------------------- ### Register Callback for Post-Bundle Execution Source: https://api.rubyonrails.org/classes/Rails/Generators/AppGenerator.html Use this method within a Rails generator to define a block of code that will execute after the `bundle install` command has completed. This is useful for tasks like Git initialization or other setup steps. ```ruby after_bundle do git add: '.' end ``` ```ruby # File railties/lib/rails/generators/rails/app/app_generator.rb, line 615 def after_bundle(&block) # :doc: @after_bundle_callbacks << block end ``` -------------------------------- ### Configure job options Source: https://api.rubyonrails.org/classes/ActiveJob/Core/ClassMethods.html Examples of setting job options such as queue, wait time, and priority before enqueuing. ```ruby VideoJob.set(queue: :some_queue).perform_later(Video.last) VideoJob.set(wait: 5.minutes).perform_later(Video.last) VideoJob.set(wait_until: Time.now.tomorrow).perform_later(Video.last) VideoJob.set(queue: :some_queue, wait: 5.minutes).perform_later(Video.last) VideoJob.set(queue: :some_queue, wait_until: Time.now.tomorrow).perform_later(Video.last) VideoJob.set(queue: :some_queue, wait: 5.minutes, priority: 10).perform_later(Video.last) ``` -------------------------------- ### POST /ActionView/Template/new Source: https://api.rubyonrails.org/classes/ActionView/Template.html Initializes a new instance of an ActionView::Template with the provided source, identifier, and handler. ```APIDOC ## POST /ActionView/Template/new ### Description Creates a new template object, setting up the source, identifier, handler, and local variables. ### Method POST ### Parameters #### Request Body - **source** (String) - Required - The template source code. - **identifier** (String) - Required - The file path or identifier for the template. - **handler** (Object) - Required - The template handler to process the source. - **locals** (Array) - Required - Local variables available to the template. - **format** (Symbol) - Optional - The format of the template (e.g., :html, :json). - **variant** (Symbol) - Optional - The variant of the template. - **virtual_path** (String) - Optional - The virtual path of the template. ### Request Example { "source": "

Hello World

", "identifier": "app/views/home/index.html.erb", "handler": "ERB", "locals": [], "format": "html" } ``` -------------------------------- ### Start Rails Console Session Source: https://api.rubyonrails.org/classes/Rails/Console.html Class method to start a new Rails console session. It creates a new instance of Rails::Console and calls its start method. ```ruby def self.start(*args) new(*args).start end ``` -------------------------------- ### Configure Setup Hook for Parallel Testing Source: https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html Use this hook for setup tasks after forking but before tests run, such as database creation. Not available with threaded parallelization. Add this to your test_helper.rb. ```ruby class ActiveSupport::TestCase parallelize_setup do # create databases end end ``` -------------------------------- ### ActiveJob::QueueAdapters::SneakersAdapter#new Source: https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/SneakersAdapter.html Initializes a new instance of the SneakersAdapter. ```APIDOC ## Method: new ### Description Initializes the Sneakers adapter with a new monitor instance. ### Signature `new()` ### Implementation ```ruby def initialize @monitor = Monitor.new end ``` ``` -------------------------------- ### Initialize KeyProvider Source: https://api.rubyonrails.org/classes/ActiveRecord/Encryption/KeyProvider.html Initializes a new KeyProvider instance with a collection of keys. ```ruby # File activerecord/lib/active_record/encryption/key_provider.rb, line 11 def initialize(keys) @keys = Array(keys) end ``` -------------------------------- ### Configuration Examples Source: https://api.rubyonrails.org/classes/Rails/Rack/SilenceRequest.html Examples of how to configure the SilenceRequest middleware in your Rails application. ```APIDOC ## Configuration ### Inserting Middleware with a Specific Path This example shows how to insert the `Rails::Rack::SilenceRequest` middleware before `Rails::Rack::Logger` and configure it to silence requests to the `/up` path. ```ruby config.middleware.insert_before `Rails::Rack::Logger`, `Rails::Rack::SilenceRequest`, path: "/up" ``` ### Inserting Middleware with a Regular Expression Path This example demonstrates configuring the middleware to silence requests whose paths match the regular expression `/test$/`. ```ruby config.middleware.insert_before `Rails::Rack::Logger`, `Rails::Rack::SilenceRequest`, path: /test$/ ``` ### Configuring the Healthcheck Path Globally Alternatively, you can configure the healthcheck path globally using `config.silence_healthcheck_path`. ```ruby config.silence_healthcheck_path = "/up" ``` ## Class: Rails::Rack::SilenceRequest ### Description Allows you to silence requests made to a specific path. This is useful for preventing recurring requests like health checks from clogging the logging. ### Methods #### `initialize(app, path:)` Initializes the middleware with the application instance and the path to silence. - **app** - The Rack application. - **path** (String or Regexp) - The path to silence requests for. #### `call(env)` Processes the incoming request. - **env** - The Rack environment hash. If the request path matches the configured path, the request is logged silently. Otherwise, the request is processed normally. ```ruby # File railties/lib/rails/rack/silence_request.rb, line 27 def call(env) if @path === env["PATH_INFO"] Rails.logger.silence { @app.call(env) } else @app.call(env) end end ``` ``` -------------------------------- ### Example: Render and Assert HTML Content Source: https://api.rubyonrails.org/classes/ActionView/TestCase/Behavior/ClassMethods.html Demonstrates rendering an article partial and asserting its HTML content using `rendered.html` and `assert_pattern`. ```ruby test "renders HTML" do article = Article.create!(title: "Hello, world") render partial: "articles/article", locals: { article: article } assert_pattern { rendered.html.at("main h1") => { content: "Hello, world" } } end ``` -------------------------------- ### Request Format Examples Source: https://api.rubyonrails.org/classes/ActionController/MimeResponds.html Examples of URL-encoded and XML-encoded request formats. ```text person[name]=...&person[company][name]=...&... ``` ```xml ... ... ``` -------------------------------- ### Initialize a new Connection Source: https://api.rubyonrails.org/classes/ActionCable/Connection/Base.html The constructor sets up the server, environment, worker pool, and internal components like subscriptions and message buffers. ```ruby # File actioncable/lib/action_cable/connection/base.rb, line 67 def initialize(server, env, coder: ActiveSupport::JSON) @server, @env, @coder = server, env, coder @worker_pool = server.worker_pool @logger = new_tagged_logger @websocket = ActionCable::Connection::WebSocket.new(env, self, event_loop) @subscriptions = ActionCable::Connection::Subscriptions.new(self) @message_buffer = ActionCable::Connection::MessageBuffer.new(self) @_internal_subscriptions = nil @started_at = Time.now end ``` -------------------------------- ### Start Event Notification Source: https://api.rubyonrails.org/classes/ActiveSupport/Notifications/Instrumenter.html Sends a start notification for an event using the notifier. ```ruby def start(name, payload) @notifier.start name, @id, payload end ```