### Example GET Request with Parameters Source: https://api.rubyonrails.org/v8.1.3/classes/ActionController/TestCase/Behavior.html Demonstrates simulating a GET request with parameters, session data, and a flash message. ```ruby get :show, params: { id: 7 }, session: { user_id: 1 }, flash: { notice: 'This is flash message' } ``` -------------------------------- ### Example Test Case with Setup and Teardown Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Testing/SetupAndTeardown.html Demonstrates how to use the `setup` and `teardown` callbacks within an `ActiveSupport::TestCase`. These callbacks are executed before and after each test method, respectively. ```ruby class ExampleTest < ActiveSupport::TestCase setup do # ... end teardown do # ... end end ``` -------------------------------- ### Parameterized Mailer Example Source: https://api.rubyonrails.org/v8.1.3/classes/ActionMailer/Parameterized.html Demonstrates how to use parameterized mailers to consolidate setup logic and default mail options, making mailer definitions more concise. ```ruby class InvitationsMailer < ApplicationMailer before_action { @inviter, @invitee = params[:inviter], params[:invitee] } before_action { @account = params[:inviter].account } default to: -> { @invitee.email_address }, from: -> { common_address(@inviter) }, reply_to: -> { @inviter.email_address_with_name } def account_invitation mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})" end def project_invitation @project = params[:project] @summarizer = ProjectInvitationSummarizer.new(@project.bucket) mail subject: "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})" end def bulk_project_invitation @projects = params[:projects].sort_by(&:name) mail subject: "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})" end end InvitationsMailer.with(inviter: person_a, invitee: person_b).account_invitation.deliver_later ``` -------------------------------- ### Example Usage of VideoAnalyzer Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage/Analyzer/VideoAnalyzer.html Demonstrates how to instantiate and use the VideoAnalyzer to get metadata from a blob. This example shows the expected output format. ```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 } ``` -------------------------------- ### Import and Start Active Storage (NPM) Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage.html Import and start Active Storage using its JavaScript API when installed via the npm package. ```javascript import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start() ``` -------------------------------- ### setup(*args, &block) Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Testing/SetupAndTeardown/ClassMethods.html Adds a callback that runs before the `TestCase#setup` method. This is useful for defining pre-test setup routines. ```APIDOC ## setup(*args, &block) ### Description Adds a callback that runs before the `TestCase#setup` method. This is useful for defining pre-test setup routines. ### Method `setup` ### Parameters * `*args`: Arguments to be passed to the callback. * `&block`: A block of code to be executed as the callback. ``` -------------------------------- ### Define a setup callback in Ruby Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Testing/SetupAndTeardown/ClassMethods.html Adds a callback that runs before the `TestCase#setup` method. Use this to define pre-test setup logic. ```ruby def setup(*args, &block) set_callback(:setup, :before, *args, &block) end ``` -------------------------------- ### Rails::DBConsole#start Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/DBConsole.html Starts the database console session using the determined configuration. ```APIDOC ## Rails::DBConsole#start ### Description Initiates the database console session. It uses the `db_config` and options to connect to the appropriate database and launch the console interface. Handles potential errors during adapter loading or connection. ### Method `start()` ### Raises - `NotImplementedError`, `ActiveRecord::AdapterNotFound`, `LoadError` - If the database adapter is not implemented, found, or cannot be loaded. ### Source `railtie/lib/rails/commands/dbconsole/dbconsole_command.rb` ``` -------------------------------- ### Starting an Event with Handle Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Fanout/Handle.html The 'start' method initializes the event state to 'started' and notifies registered groups. It must be called exactly once before 'finish'. ```ruby # File activesupport/lib/active_support/notifications/fanout.rb, line 241 def start ensure_state! :initialized @state = :started iterate_guarding_exceptions(@groups) do |group| group.start(@name, @id, @payload) end end ``` -------------------------------- ### Event#start! Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Records the current time and CPU/GC/allocation information to mark the start of the event. ```APIDOC ### start!() Record information at the time this event starts. ``` -------------------------------- ### start Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Fanout.html Starts a notification process, creating a handle for the event. ```APIDOC ## start ### Description Starts a notification process, creating a handle for the event. ### Method `start(name, id, payload)` ### Parameters #### Path Parameters - **name** (String) - Required - The name of the notification. - **id** (String) - Required - The unique identifier for the event. - **payload** (Object) - Required - The data associated with the event. ### Response #### Success Response Starts the notification process and returns a handle. ### Request Example ```ruby fanout.start('render_template', 'abc', { partial: 'index' }) ``` ``` -------------------------------- ### Non-Parameterized Mailer Example Source: https://api.rubyonrails.org/v8.1.3/classes/ActionMailer/Parameterized.html Illustrates a standard mailer setup without using parameterization, defining instance variables and mail options within each method. ```ruby class InvitationsMailer < ApplicationMailer def account_invitation(inviter, invitee) @account = inviter.account @inviter = inviter @invitee = invitee subject = "#{@inviter.name} invited you to their Basecamp (#{@account.name})" mail \ subject: subject, to: invitee.email_address, from: common_address(inviter), reply_to: inviter.email_address_with_name end def project_invitation(project, inviter, invitee) @account = inviter.account @project = project @inviter = inviter @invitee = invitee @summarizer = ProjectInvitationSummarizer.new(@project.bucket) subject = "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})" mail \ subject: subject, to: invitee.email_address, from: common_address(inviter), reply_to: inviter.email_address_with_name end def bulk_project_invitation(projects, inviter, invitee) @account = inviter.account @projects = projects.sort_by(&:name) @inviter = inviter @invitee = invitee subject = "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})" mail \ subject: subject, to: invitee.email_address, from: common_address(inviter), reply_to: inviter.email_address_with_name end end InvitationsMailer.account_invitation(person_a, person_b).deliver_later ``` -------------------------------- ### Custom App Builder Example Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/AppBuilder.html Example of a custom app builder that adds the 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 ``` -------------------------------- ### Get Event Start Time Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Returns the start time of the event in seconds. Returns nil if the event has not started. ```ruby def time @time / 1000.0 if @time end ``` -------------------------------- ### Get Current Week Start Source: https://api.rubyonrails.org/v8.1.3/classes/Date.html Retrieves the configured start of the week for the current request. Defaults to :monday if not explicitly set. ```ruby def beginning_of_week ::ActiveSupport::IsolatedExecutionState[:beginning_of_week] || beginning_of_week_default || :monday end ``` -------------------------------- ### ActionCable::Server::Base.new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Server/Base.html Initializes a new ActionCable::Server::Base instance with the provided configuration. ```APIDOC ## ActionCable::Server::Base.new ### Description Initializes a new ActionCable::Server::Base instance with the provided configuration. ### Method POST ### Endpoint `/new` ### Parameters #### Request Body - **config** (Object) - Required - The configuration object for the server. Defaults to `self.class.config`. ### Request Example ```json { "config": { "connection_class": "ActionCable::Connection::Base", "logger": "#" } } ``` ### Response #### Success Response (200) - **server** (ActionCable::Server::Base) - The newly created server instance. ### Response Example ```json { "server": "#" } ``` ``` -------------------------------- ### Example Usage of human_attribute_name Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveModel/Translation.html Shows a direct example of calling human_attribute_name on a class to get a human-readable version of an attribute name. ```ruby Person.human_attribute_name("first_name") # => "First name" ``` -------------------------------- ### setup_with_controller Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/TestCase/Behavior.html Sets up the test case with a controller instance. ```APIDOC ## Instance Public methods ### **setup_with_controller**() Source: show | on GitHub ``` # 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 ``` ``` -------------------------------- ### Full-Stack Broadcasting Example Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Server/Broadcasting.html Demonstrates how to set up a channel to receive broadcasts and how to send broadcasts from the server. Includes client-side JavaScript for handling received messages. ```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'] }) } }) ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Testing/Parallelization/Server.html Initializes a new Server instance. It sets up internal data structures for managing the test queue, active workers, and in-flight tests. ```APIDOC ## new ### Description Initializes a new Server instance. It sets up internal data structures for managing the test queue, active workers, and in-flight tests. ### Method new ### Parameters None ### Response None ``` -------------------------------- ### Initializing and Adding Paths Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Paths/Root.html Demonstrates how to initialize a Root object and add a new path with eager loading enabled. ```ruby root = Root.new "/rails" root.add "app/controllers", eager_load: true ``` -------------------------------- ### Worker#start Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Testing/Parallelization/Worker.html Starts the worker process. This method forks a new process, sets up the DRb connection, runs initial setup hooks, and begins processing jobs from the queue. ```APIDOC ## Worker#start() ### Description Starts the worker process by forking a child process. The child process sets up the DRb service connection, registers itself with the queue, runs any initial setup hooks (catching exceptions), and then enters the `work_from_queue` loop. It ensures cleanup hooks are run and the worker is stopped from the queue upon completion or interruption. ### Method start ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Encryption/KeyProvider.html Initializes a new KeyProvider instance with a given set of keys. The keys can be a single key or an array of keys. ```APIDOC ## new(keys) ### Description Initializes a new KeyProvider instance with a given set of keys. The keys can be a single key or an array of keys. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Error Handling None ``` -------------------------------- ### Get Beginning of Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html Returns a new date/time representing the start of this week. Assumes week starts on the given `start_day`, defaulting to `Date.beginning_of_week`. 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 ``` -------------------------------- ### Demo Integration Test Example Source: https://api.rubyonrails.org/v8.1.3/classes/ActionDispatch/Response.html This example demonstrates how to use integration tests to inspect the response body of a controller action. It utilizes `get` to make a request and `response.body` to access the response content. ```ruby class DemoControllerTest < ActionDispatch::IntegrationTest def test_print_root_path_to_console get('/') puts response.body end end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/TestCase/Behavior/ClassMethods.html Initializes a new instance of the test case, including helper modules. ```APIDOC ## new(*) ### Description Initializes a new instance of the test case, including helper modules. ### Method `new(*)` ### Source `actionview/lib/action_view/test_case.rb` ``` -------------------------------- ### Rails::Server#start Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Server.html Starts the Rails server, handling interrupt signals, creating temporary directories, setting up caching, and logging. ```APIDOC ## Rails::Server#start ### Description Initiates the Rails server process. It includes signal handling, temporary directory creation, development caching setup, and logging configuration before starting the underlying Rack server. ### Method `start(after_stop_callback = nil)` ### Parameters - **after_stop_callback** (Proc) - An optional callback to be executed after the server stops. ### Source File: railties/lib/rails/commands/server/server_command.rb, line 32 ``` -------------------------------- ### Get Event CPU Time Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Returns the CPU time in milliseconds consumed by the event between `start!` and `finish!`. ```ruby def cpu_time @cpu_time_finish - @cpu_time_start end ``` -------------------------------- ### Rails::Application.new Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Application.html Initializes a new Rails application instance. ```APIDOC ## Rails::Application.new ### Description Initializes a new Rails application instance with optional initial values and a configuration block. ### Method `new(initial_variable_values = {}, &block)` ### Parameters - `initial_variable_values` (Hash) - Optional initial values for the application. - `block` (Proc) - Optional block to configure the application. ### Returns A new instance of Rails::Application. ``` -------------------------------- ### Get Event Allocations Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Returns the number of memory allocations that occurred between the `start!` and `finish!` calls for this event. ```ruby def allocations @allocation_count_finish - @allocation_count_start end ``` -------------------------------- ### Start DB Console Instance Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/DBConsole.html Starts the database console session using the adapter class and database configuration. Rescues and aborts on common database connection errors. ```ruby def start adapter_class.dbconsole(db_config, @options) rescue NotImplementedError, ActiveRecord::AdapterNotFound, LoadError => error abort error.message end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/ConnectionAdapters/TrilogyAdapter.html Initializes a new TrilogyAdapter instance. It handles configuration, including socket usage and prepared statements, and calls the superclass initializer. ```APIDOC ## new(config, *) ### Description Initializes a new TrilogyAdapter instance. It handles configuration, including socket usage and prepared statements, and calls the superclass initializer. ### Method new ### Parameters #### Path Parameters - **config** (Hash) - Required - Configuration options for the adapter. ### Request Example ```ruby ActiveRecord::ConnectionAdapters::TrilogyAdapter.new({ host: 'localhost', username: 'root', database: 'my_db' }) ``` ### Response #### Success Response - **TrilogyAdapter** - A new instance of the TrilogyAdapter. ``` -------------------------------- ### assert_has_no_stream_for Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Channel/TestCase/Behavior.html Asserts that the stream associated with a given object has not been started. It leverages `broadcasting_for` to get the stream name. ```APIDOC ## assert_has_no_stream_for(object) ### Description Asserts that the stream associated with a given object has not been started. It leverages `broadcasting_for` to get the stream name. ### Method `assert_has_no_stream_for` ### Parameters #### Arguments - **object**: The object for which to check the associated stream. ``` -------------------------------- ### Get Beginning of Quarter Source: https://api.rubyonrails.org/v8.1.3/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 ``` ```Ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 139 def beginning_of_quarter first_quarter_month = month - (2 + month) % 3 beginning_of_month.change(month: first_quarter_month) end ``` -------------------------------- ### Initialize ActionCable Subscription Adapter Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/SubscriptionAdapter/Base.html Initializes the subscription adapter with the server instance and sets up the logger. ```ruby def initialize(server) @server = server @logger = @server.logger end ``` -------------------------------- ### Get Connection Statistics Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Connection/Base.html Returns connection statistics including identifier, start time, subscriptions, and request ID. ```ruby # File actioncable/lib/action_cable/connection/base.rb, line 138 def statistics { identifier: connection_identifier, started_at: @started_at, subscriptions: subscriptions.identifiers, request_id: @env["action_dispatch.request_id"] } end ``` -------------------------------- ### ActionView::Template::Sources::File#initialize Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/Template/Sources/File.html Initializes a new instance of ActionView::Template::Sources::File with the specified filename. ```APIDOC ## ActionView::Template::Sources::File#initialize ### Description Initializes a new instance of ActionView::Template::Sources::File with the specified filename. ### Method new ### Parameters #### Path Parameters - **filename** (String) - Required - The path to the template file. ``` -------------------------------- ### Audio Analyzer Metadata Extraction Example Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage/Analyzer/AudioAnalyzer.html Demonstrates how to use the AudioAnalyzer to get metadata from a blob. Requires FFmpeg. ```ruby ActiveStorage::Analyzer::AudioAnalyzer.new(blob).metadata # => { duration: 5.0, bit_rate: 320340, sample_rate: 44100, tags: { encoder: "Lavc57.64", ... } } ``` -------------------------------- ### Get Children Paths Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Paths/Path.html Retrieves all paths from the root that start with the current path, excluding the current path itself. The results are sorted. ```ruby def children keys = @root.keys.find_all { |k| k.start_with?(@current) && k != @current } @root.values_at(*keys.sort) end ``` -------------------------------- ### Examples of Setting Job Options Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveJob/Core/ClassMethods.html Demonstrates various ways to use the `set` method to configure job enqueuing with different options like queue, wait time, and priority. ```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) ``` -------------------------------- ### Example: Using column_for_attribute Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/ModelSchema/ClassMethods.html Demonstrates how to use `column_for_attribute` to get column information for an existing attribute and how it behaves for a non-existent attribute. ```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) # => #, ...> ``` -------------------------------- ### Rails::Server.new Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Server.html Initializes a new Rails::Server instance. It accepts an optional options hash to configure the server and sets the Rails environment. ```APIDOC ## Rails::Server.new ### Description Initializes a new Rails::Server instance with optional configuration. ### Method `new(options = nil)` ### Parameters - **options** (Hash) - Optional hash to set default server options. ### Source File: railties/lib/rails/commands/server/server_command.rb, line 18 ``` -------------------------------- ### Example Test Case for Active Record Logging Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/LogSubscriber/TestHelper.html This example demonstrates how to use ActiveSupport::LogSubscriber::TestHelper in a test case to verify Active Record query logging. It includes setup for attaching the subscriber and assertions for checking logged messages. ```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 ``` -------------------------------- ### ActionView::Renderer#new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/Renderer.html Initializes a new Renderer instance with a given lookup context. ```APIDOC ## new(lookup_context) ### Description Initializes a new Renderer instance with a given lookup context. ### Parameters #### Path Parameters - **lookup_context** (Object) - Required - The lookup context to be used for rendering. ``` -------------------------------- ### new(app, options = {}) Source: https://api.rubyonrails.org/v8.1.3/classes/ActionDispatch/Session/Compatibility.html Initializes a new session store instance. It sets a default session key if none is provided and calls the superclass initializer. ```APIDOC ## new(app, options = {}) ### Description Initializes a new session store instance. It sets a default session key if none is provided and calls the superclass initializer. ### Method `initialize` ### Parameters - **app**: The Rack application. - **options** (Hash) - Optional. Configuration options for the session store. If `:key` is not provided, it defaults to `"_session_id"`. ``` -------------------------------- ### Get Beginning of Hour with beginning_of_hour() Source: https://api.rubyonrails.org/v8.1.3/classes/DateTime.html Returns a new DateTime object set to the start of the hour (hh:00:00). Also aliased as `at_beginning_of_hour`. ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 146 def beginning_of_hour change(min: 0) end ``` -------------------------------- ### Get Array Tail from Position Source: https://api.rubyonrails.org/v8.1.3/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"] %w( a b c d ).from(2) # => ["c", "d"] %w( a b c d ).from(10) # => [] %w().from(0) # => [] %w( a b c d ).from(-2) # => ["c", "d"] %w( a b c ).from(-10) # => [] ``` ```ruby def from(position) self[position, length] || [] end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionMailer/Base.html Initializes a new Action Mailer instance, setting up internal mailer state. ```APIDOC ## new() ### Description Initializes a new Action Mailer instance. ### Method `new` ### Returns ActionMailer::Base - A new instance of Action Mailer. ``` -------------------------------- ### Get Sunday of the Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html Returns the Sunday of the current week, assuming the week starts on Monday. For `DateTime` objects, the time is set to 23:59:59. ```Ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 290 def sunday end_of_week(:monday) end ``` -------------------------------- ### initialize Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html Initializes and connects a PostgreSQL adapter. This method sets up the connection parameters and prepares the adapter for use. ```APIDOC ## initialize ### Description Initializes and connects a PostgreSQL adapter. This method sets up the connection parameters and prepares the adapter for use. ### Method Signature `initialize(...)` ### Internal Details This method configures connection parameters, maps ActiveRecord parameter names to PostgreSQL driver names, and forwards valid parameters to the `PG::Connection.connect` method. It also initializes internal state variables for type mapping and connection management. ``` -------------------------------- ### Get Beginning of Minute with beginning_of_minute() Source: https://api.rubyonrails.org/v8.1.3/classes/DateTime.html Returns a new DateTime object set to the start of the minute (hh:mm:00). Also aliased as `at_beginning_of_minute`. ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 158 def beginning_of_minute change(sec: 0) end ``` -------------------------------- ### Basic Redirect Examples Source: https://api.rubyonrails.org/v8.1.3/classes/ActionController/Redirecting.html Demonstrates various ways to use `redirect_to` with different targets like actions, objects, URLs, and procs. ```ruby redirect_to action: "show", id: 5 redirect_to @post redirect_to "http://www.rubyonrails.org" redirect_to "/images/screenshot.jpg" redirect_to posts_url redirect_to proc { edit_post_url(@post) } ``` -------------------------------- ### Get Event GC Time Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Returns the time spent in garbage collection (GC) in milliseconds during the event's execution, between `start!` and `finish!`. ```ruby def gc_time (@gc_time_finish - @gc_time_start) / 1_000_000.0 end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage/Service/GCSService.html Initializes a new GCSService instance. It takes a boolean `public` argument and a hash of configuration options. ```APIDOC ## new(public: false, config) ### Description Initializes a new GCSService instance. It takes a boolean `public` argument and a hash of configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method `initialize` ### Endpoint N/A (Constructor) ### Request Example ```ruby service = ActiveStorage::Service::GCSService.new(public: true, bucket: 'your-bucket-name') ``` ### Response N/A (Constructor) ``` -------------------------------- ### parallelize_setup Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/TestCase.html Defines a setup hook that runs after parallel test processes are forked but before tests begin execution. This is ideal for tasks like setting up multiple databases or other per-process configurations. ```APIDOC ## parallelize_setup(&block) ### Description Setup hook for parallel testing. This can be used if you have multiple databases or any behavior that needs to be run after the process is forked but before the tests run. Note: this feature is not available with the threaded parallelization. ### Usage ```ruby class ActiveSupport::TestCase parallelize_setup do # create databases end end ``` ``` -------------------------------- ### Calculate Event Duration Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/Notifications/Event.html Calculates the total duration of the event in milliseconds, from its start to its end time. This example demonstrates how to subscribe to an event and then access 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 def duration @end - @time end ``` -------------------------------- ### Access ActiveRecord schema_cache_ignored_tables Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord.html A list of tables or regex patterns to ignore when dumping the schema cache. For example, `[/^_/]` will ignore tables starting with an underscore. ```ruby singleton_class.attr_accessor :schema_cache_ignored_tables ``` -------------------------------- ### Font Path Examples Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/Helpers/AssetUrlHelper.html Demonstrates how to compute paths for font assets using `font_path`. ```ruby font_path("font") # => /fonts/font font_path("font.ttf") # => /fonts/font.ttf font_path("dir/font.ttf") # => /fonts/dir/font.ttf font_path("/dir/font.ttf") # => /dir/font.ttf font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf ``` -------------------------------- ### Setup System Test Directory Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/AppBuilder.html Sets up the 'test/system' directory and the 'application_system_test_case.rb' template if the application is in a development container and depends on system tests. ```ruby def system_test if devcontainer? && depends_on_system_test? empty_directory_with_keep_file "test/system" template "test/application_system_test_case.rb" end end ``` -------------------------------- ### Get Beginning of Day with beginning_of_day() Source: https://api.rubyonrails.org/v8.1.3/classes/DateTime.html Returns a new DateTime object set to the start of the day (00:00:00). This method is also aliased as `midnight`, `at_midnight`, and `at_beginning_of_day`. ```ruby # File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 122 def beginning_of_day change(hour: 0) end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionController/UrlFor.html Initializes the UrlFor module, setting up internal URL options. ```APIDOC ## new ### Description Initializes the UrlFor module, setting up internal URL options. ### Method `new(...)` ### Parameters This method accepts variable arguments (`...`). Specific parameter details are not provided in the source. ### Code Example ```ruby # File actionpack/lib/action_controller/metal/url_for.rb, line 32 def initialize(...) super @_url_options = nil end ``` ``` -------------------------------- ### Get AES-256-GCM Key Length Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Encryption/Cipher/Aes256Gcm.html Retrieves the required key length for the AES-256-GCM cipher. This is useful for ensuring the correct key size is used during encryption setup. ```ruby def key_length OpenSSL::Cipher.new(CIPHER_TYPE).key_len end ``` -------------------------------- ### Processing Batches from a Specific Starting Point Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Batches.html Shows how to use the `:start` option to begin batch processing from a specific record ID. This is useful for distributing work across multiple processes. ```ruby # Let's process from record 10_000 on. Person.in_batches(start: 10_000).update_all(awesome: true) ``` -------------------------------- ### Example Usage of ImageMagick Analyzer Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage/Analyzer/ImageAnalyzer.html Demonstrates how to use the ImageMagick analyzer to get image metadata, including width and height. This is useful for displaying or processing images. ```ruby ActiveStorage::Analyzer::ImageAnalyzer::ImageMagick.new(blob).metadata # => { width: 4104, height: 2736 } ``` -------------------------------- ### Get MySQL2 Base Package Name Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Generators/Database/MySQL2.html Returns the default client package name for MySQL. Use this to specify the base package required for MySQL client installation. ```ruby # File railties/lib/rails/generators/database.rb, line 153 def base_package "default-mysql-client" end ``` -------------------------------- ### initialize Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Migration.html Initializes a new Migration instance. ```APIDOC ## new ### Description Initializes a new Migration instance with an optional name and version. ### Method POST ### Endpoint `/migrations/new` ### Parameters #### Request Body - **name** (string) - Optional - The name of the migration. - **version** (string) - Optional - The version of the migration. ``` -------------------------------- ### Image Path Examples Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/Helpers/AssetUrlHelper.html Illustrates computing paths for image assets using `image_path`, including nested images and external URLs. ```ruby image_path("edit") # => "/assets/edit" image_path("edit.png") # => "/assets/edit.png" image_path("icons/edit.png") # => "/assets/icons/edit.png" image_path("/icons/edit.png") # => "/icons/edit.png" image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png" ``` -------------------------------- ### Get Monday of the Current Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html The `monday` method returns the Monday of 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 ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Channel/ConnectionStub.html Initializes a new ConnectionStub instance. It sets up the server, transmissions, subscriptions, identifiers, and logger. It also dynamically defines methods for each identifier provided. ```APIDOC ## new(identifiers = {}) ### Description Initializes a new ConnectionStub instance. It sets up the server, transmissions, subscriptions, identifiers, and logger. It also dynamically defines methods for each identifier provided. ### Method `new` ### Parameters * **identifiers** (Hash) - Optional - A hash where keys are identifier names and values are their corresponding values. These will be defined as singleton methods on the stub. ### Code Example ```ruby stub = ActionCable::Channel::ConnectionStub.new(user_id: 1) ``` ``` -------------------------------- ### Get Range for Entire Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html The `all_week` method returns a `Range` object representing the entire current week. The start day of the week can be specified, defaulting to `Date.beginning_of_week`. ```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 ``` -------------------------------- ### Get Action View Gem Version Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView.html Retrieves the currently installed version of the Action View gem as a `Gem::Version` object. Useful for dependency checking or logging. ```ruby # File actionview/lib/action_view/gem_version.rb, line 5 def self.gem_version Gem::Version.new VERSION::STRING end ``` -------------------------------- ### Setup controller request and response Source: https://api.rubyonrails.org/v8.1.3/classes/ActionController/TestCase/Behavior.html Initializes the controller, request, and response objects for testing. It handles setting up the appropriate response class (e.g., `LiveTestResponse` for `ActionController::Live`) and ensures the controller's request and params are set. ```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 ``` -------------------------------- ### Alternative Nested Association Setup Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Associations/ClassMethods.html Presents an alternative way to set up nested associations where intermediate models also define their respective :through associations. This achieves the same result as the previous example. ```ruby class Author < ActiveRecord::Base has_many :posts has_many :commenters, through: :posts end class Post < ActiveRecord::Base has_many :comments has_many :commenters, through: :comments end class Comment < ActiveRecord::Base belongs_to :commenter end ``` -------------------------------- ### Get Fixture File Name Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Generators/NamedBase.html Determines the file name for fixtures, using the pluralized table name if configured, otherwise the singular file name. Essential for test data setup. ```ruby def fixture_file_name # :doc: @fixture_file_name ||= (pluralize_table_names? ? plural_file_name : file_name) end ``` -------------------------------- ### Initialize Rails::Server Source: https://api.rubyonrails.org/v8.1.3/classes/Rails/Server.html Initializes the Rails::Server with provided options and sets the environment. ```ruby def initialize(options = nil) @default_options = options || {} super(@default_options) set_environment end ``` -------------------------------- ### Get End of Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html Returns a new date/time representing the end of this week. Assumes week starts on the given `start_day`, defaulting to `Date.beginning_of_week`. DateTime objects have their time set to 23:59:59. ```Ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 283 def end_of_week(start_day = Date.beginning_of_week) last_hour(days_since(6 - days_to_week_start(start_day))) end ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/TestCase/TestController.html Initializes a new instance of TestController, setting up test request and response objects. ```APIDOC ## POST new ### Description Initializes a new instance of TestController, setting up test request and response objects. ### Method POST ### Endpoint /new ### Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - Indicates successful initialization. #### Response Example { "message": "TestController initialized successfully" } ``` -------------------------------- ### Example Usage of DatabaseTasks Outside Rails Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/Tasks/DatabaseTasks.html Demonstrates how to configure and use DatabaseTasks for common database operations when not running within a full 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') ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionDispatch/Session/CacheStore.html Initializes a new CacheStore instance. It configures the cache, expiration time, and collision checking based on the provided options. ```APIDOC ## new(app, options = {}) ### Description Initializes a new CacheStore instance. It configures the cache, expiration time, and collision checking based on the provided options. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **app**: The application instance. * **options** (Hash) - Optional. A hash of options to configure the store. * **cache**: The cache to use. Defaults to `Rails.cache`. * **expire_after**: The length of time a session will be stored before automatically expiring. Defaults to the cache's `:expires_in` option. * **check_collisions**: Whether to check if newly generated session IDs are already in use. Defaults to `false`. ``` -------------------------------- ### Get Previous Week Source: https://api.rubyonrails.org/v8.1.3/classes/DateAndTime/Calculations.html Returns a new date/time for the given day in the previous week. The start of the week can be configured. For `DateTime` objects, the time is set to 0:00 unless `same_time` is true. Aliased as `last_week`. ```Ruby # File activesupport/lib/active_support/core_ext/date_and_time/calculations.rb, line 223 def prev_week(start_day = Date.beginning_of_week, same_time: false) result = first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day))) same_time ? copy_time_to(result) : result end ``` -------------------------------- ### Basic Connection Setup Source: https://api.rubyonrails.org/v8.1.3/classes/ActionCable/Connection/Base.html Defines a basic Action Cable connection class that identifies connections by user and handles connection establishment and verification. ```ruby module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_user logger.add_tags current_user.name end def disconnect # Any cleanup work needed when the cable connection is cut. end private def find_verified_user User.find_by_identity(cookies.encrypted[:identity_id]) || reject_unauthorized_connection end end end ``` -------------------------------- ### Minimal ActiveModel::AttributeMethods Implementation Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveModel/AttributeMethods.html A basic example demonstrating how to include ActiveModel::AttributeMethods and define attribute methods with prefixes, suffixes, and dynamic methods. This setup allows for attribute access as if they were first-class methods. ```ruby class Person include ActiveModel::AttributeMethods attribute_method_affix prefix: 'reset_', suffix: '_to_default!' attribute_method_suffix '_contrived?' attribute_method_prefix 'clear_' define_attribute_methods :name attr_accessor :name def attributes { 'name' => @name } end private def attribute_contrived?(attr) true end def clear_attribute(attr) send("#{attr}=", nil) end def reset_attribute_to_default!(attr) send("#{attr}=", 'Default Name') end end ``` -------------------------------- ### ParameterFilter Initialization Examples Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveSupport/ParameterFilter.html Demonstrates various ways to initialize ParameterFilter with different types of filters, including string, regex, and proc-based filters, as well as nested key filtering. ```ruby # Replaces values with "[FILTERED]" for keys that match /password/i. ActiveSupport::ParameterFilter.new([:password]) ``` ```ruby # Replaces values with "[FILTERED]" for keys that match /foo|bar/i. ActiveSupport::ParameterFilter.new([:foo, "bar"]) ``` ```ruby # Replaces values for the exact key "pin" and for keys that begin with # "pin_". Does not match keys that otherwise include "pin" as a # substring, such as "shipping_id". ActiveSupport::ParameterFilter.new([/\Apin\z/, /\Apin_/]) ``` ```ruby # Replaces the value for :code in `{ credit_card: { code: "xxxx" } }`. # Does not change `{ file: { code: "xxxx" } }`. ActiveSupport::ParameterFilter.new(["credit_card.code"]) ``` ```ruby # Reverses values for keys that match /secret/i. ActiveSupport::ParameterFilter.new([-> (k, v) do v.reverse! if /secret/i.match?(k) end]) ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActionDispatch/Integration/Runner.html Initializes a new instance of the Runner. It sets up the integration session to be nil initially. ```APIDOC ## new(*args, &blk) ### Description Initializes a new instance of the Runner. It sets up the integration session to be nil initially. ### Method `initialize` ### Parameters * `*args`: Variable number of arguments. * `&blk`: A block of code to be executed. ### Source File: actionpack/lib/action_dispatch/testing/integration.rb, line 343 ``` -------------------------------- ### Defining Member Routes in Resources Source: https://api.rubyonrails.org/v8.1.3/classes/ActionDispatch/Routing/Mapper/Resources.html Use the `member` block within a `resources` definition to add routes that apply to a specific member of a resource. This example shows how to add a `GET` route for a 'preview' action. ```Ruby resources :photos do member do get 'preview' end end ``` -------------------------------- ### Using current_cycle to get the current cycle value Source: https://api.rubyonrails.org/v8.1.3/classes/ActionView/Helpers/TextHelper.html The `current_cycle` method returns the current cycle string after a cycle has been started. This is useful for complex table highlighting or when the current cycle string is needed in multiple places. ```Ruby <%# Alternate background colors %> <% @items = [1,2,3,4] %> <% @items.each do |item| %>
"> "item" %>
<% end %> ``` -------------------------------- ### new Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveStorage/Service/S3Service.html Initializes a new S3 service instance. Configures the S3 client, bucket, and upload options, including multipart upload thresholds and ACL settings. ```APIDOC ## new(bucket:, upload: {}, public: false, **options) ### Description Initializes a new S3 service instance. Configures the S3 client, bucket, and upload options, including multipart upload thresholds and ACL settings. ### Parameters - **bucket** (String) - Required - The name of the S3 bucket to use. - **upload** (Hash) - Optional - Options for uploads, such as `multipart_threshold`. - **public** (Boolean) - Optional - If true, sets the ACL to public-read. - **options** (Hash) - Optional - Additional options to pass to the AWS S3 client. ``` -------------------------------- ### Start Transaction Instrumentation Source: https://api.rubyonrails.org/v8.1.3/classes/ActiveRecord/ConnectionAdapters/TransactionInstrumenter.html Starts the transaction instrumentation. Raises an error if already started. It instruments the start event and builds a handle for further instrumentation. ```ruby def start raise InstrumentationAlreadyStartedError.new("Called start on an already started transaction") if @started @started = true ActiveSupport::Notifications.instrument("start_transaction.active_record", @base_payload) @payload = @base_payload.dup # We dup because the payload for a given event is mutated later to add the outcome. @handle = ActiveSupport::Notifications.instrumenter.build_handle("transaction.active_record", @payload) @handle.start end ```