### Install Dependencies and Run Tests Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Install project dependencies using Bundler and run the test suite. ```bash bundle install bundle exec rake test ``` -------------------------------- ### Install Gem and Generate Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md Install the gem using Bundler. The generator command may be available in older Rails versions. ```bash bundle install rails generate jquery:install # If available in older Rails versions ``` -------------------------------- ### Rails Engine Integration Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md Example demonstrating the automatic loading of Jquery::Rails::Engine for Rails integration. ```ruby require 'jquery-rails' # Jquery::Rails::Engine is automatically loaded ``` -------------------------------- ### Asset Pipeline Setup (application.js) Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md Configure your application.js to include jQuery and related files using Sprockets directives. ```javascript //= require jquery3 //= require jquery_ujs //= require_self //= require_tree . $(function() { console.log('jQuery is ready!'); console.log('jQuery version:', $.fn.jquery); }); ``` -------------------------------- ### Complete Form Example with Data Attributes Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md This example demonstrates a complete HTML form utilizing various data attributes for remote submission, JSON data type, confirmation messages, and dynamic button text. It also includes JavaScript event handlers for AJAX responses. ```html
Cancel
``` -------------------------------- ### Target as Argument (appendTo/prependTo) Assertion Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Tests jQuery methods where the target selector is passed as an argument, such as appendTo and prependTo. This example shows how to assert these operations and verify the appended/prepended content. ```javascript // Response: // $("
Product
").appendTo("#inventory"); // $("
New
").prependTo("#items"); ``` ```ruby assert_select_jquery :appendTo, '#inventory' do assert_select '.item', 'Product' end assert_select_jquery :prependTo, '#items' do assert_select '.header', 'New' end ``` -------------------------------- ### Rails Unit Test Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Demonstrates including the necessary module to use assert_select_jquery in a Rails unit test class. ```ruby class MyUnitTest < ActiveSupport::TestCase include Rails::Dom::Testing::Assertions::SelectorAssertions # assert_select_jquery available here too end ``` -------------------------------- ### Event Handling for User Confirmation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Provides examples of how to hook into the 'confirm' and 'confirm:complete' events to customize or prevent confirmation dialogs and log actions. ```javascript $('a.delete').on('confirm', function(e) { var sure = validateBeforeDelete(); if (!sure) { e.preventDefault(); // Prevent confirmation dialog } }); $('a.delete').on('confirm:complete', function(e, answer) { if (answer) { logDeletion(); } }); ``` -------------------------------- ### Development Asset Serving Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md In development, uncompressed JavaScript assets like jQuery are served directly. This example shows including jQuery 3 in `application.js`. ```javascript // app/assets/javascripts/application.js //= require jquery3 ``` -------------------------------- ### Rails Integration Test Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Shows how to use assert_select_jquery within a Rails integration test class. ```ruby class MyControllerTest < ActionDispatch::IntegrationTest # assert_select_jquery available here end ``` -------------------------------- ### Nested Assertions on HTML Structure Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Demonstrates deeply nested assertions within a block to verify complex HTML structures generated by jQuery. This example shows how to assert elements within elements, including attribute selectors. ```javascript // Response: // $("#modal").html("

Edit User

"); ``` ```ruby assert_select_jquery :html, '#modal' do assert_select '.header' assert_select 'h1', 'Edit User' assert_select 'form' do assert_select 'input[name=username]' end end ``` -------------------------------- ### Example Usage of Blank Inputs Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Demonstrates how to use the blankInputs function to check for missing input values in a form and access the count of blank inputs. ```javascript var missing = $.rails.blankInputs($('form')); if (missing) { // missing.length inputs are empty } ``` -------------------------------- ### Example Test Case with Selector Assertions Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md Demonstrates how to use `assert_select_jquery` within a test case by including `Rails::Dom::Testing::Assertions::SelectorAssertions`. ```ruby class MyTest < ActiveSupport::TestCase include Rails::Dom::Testing::Assertions::SelectorAssertions def test_something assert_select_jquery :show, '#notice' end end ``` -------------------------------- ### Basic Method Assertion Examples Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Demonstrates basic assertions for jQuery method calls, including calls with and without specific selectors. Shows passing and failing cases. ```javascript // Response: // $("#message").show(); // $("#notice").hide(); ``` ```ruby assert_select_jquery :show # ✓ Passes — finds $("#message").show() assert_select_jquery :show, '#message' # ✓ Passes — finds $("#message").show() assert_select_jquery :hide, '#notice' # ✓ Passes — finds $("#notice").hide() assert_select_jquery :remove, '#notice' # ✗ Fails — no remove() call found ``` -------------------------------- ### Animation Method with Option Assertion Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Asserts jQuery animation methods with specific options and selectors. This example demonstrates testing calls like .show('slide', 300) and verifies the correct option is used. ```javascript // Response: // $("#sidebar").show('slide', 300); // $("#sidebar").hide('fade', 500); ``` ```ruby assert_select_jquery :show, :slide, '#sidebar' # ✓ Passes assert_select_jquery :hide, :fade, '#sidebar' # ✓ Passes assert_select_jquery :hide, :blind, '#sidebar' # ✗ Fails — 'blind' option not found ``` -------------------------------- ### HTML Manipulation with Block Assertion Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Tests HTML manipulation using the :html method and verifies the resulting DOM structure with nested assertions. This example shows how to check for specific elements and text content within the manipulated HTML. ```javascript // Response: // $("#user-list").html("
Alice
"); ``` ```ruby assert_select_jquery :html, '#user-list' do assert_select '.user' assert_select '.name', 'Alice' end ``` -------------------------------- ### Custom AJAX Implementation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Replace the default AJAX implementation with a custom one using `$.rails.ajax`. This example uses the Fetch API. ```javascript $.rails.ajax = function(options) { return fetch(options.url, { method: options.type, body: options.data }).then(r => r.json()); }; ``` -------------------------------- ### Example Rails Application Integration Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/Rails-Engine.md Demonstrates how to add the jquery-rails gem to the Gemfile and include jQuery and jQuery-UJS in the application's JavaScript manifest, along with a basic jQuery ready function. ```ruby # Gemfile gem 'jquery-rails' # config/assets/javascripts/application.js //= require jquery3 //= require jquery_ujs //= require_tree . // Now jQuery and Rails UJS are available globally $(function() { // jQuery is ready $('a[data-confirm]').on('click', function() { // Rails UJS handles confirmation dialogs }); }); ``` -------------------------------- ### Example of Stopping Event Propagation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Shows how to prevent the default form submission behavior and stop event propagation using the stopEverything function. ```javascript $('form').on('submit', function(e) { e.preventDefault(); $.rails.stopEverything(e); }); ``` -------------------------------- ### Importmap Configuration for jQuery Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Configure Importmap to pin jQuery from a CDN. This example pins jQuery version 3.7.1 and also pins 'rails.js' with preloading enabled. ```javascript // config/importmap.rb pin "jquery", to: "https://code.jquery.com/jquery-3.7.1.min.js" pin "rails", to: "rails.js", preload: true ``` -------------------------------- ### ajax(options) Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Wrapper around jQuery's $.ajax() that can be customized. It allows for replacing the default AJAX implementation with a custom one, for example, using the Fetch API. ```APIDOC ## ajax(options) ### Description Wrapper around `$.ajax()` that can be customized. Enables replacing the default AJAX implementation. ### Parameters #### Options - **options** (Object) - jQuery AJAX options ### Returns jqXHR ### Example ```javascript $.rails.ajax = function(options) { return fetch(options.url, { method: options.type, body: options.data }).then(r => r.json()); }; ``` ``` -------------------------------- ### Add jquery-rails Gem to Gemfile Source: https://github.com/rails/jquery-rails/blob/master/README.md To install the jquery-rails gem, add the specified line to your application's Gemfile. ```ruby gem 'jquery-rails' ``` -------------------------------- ### Custom Confirmation Dialog Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Implement a custom modal dialog for confirmations instead of the browser's default `confirm()` function. This example uses a Promise to handle the asynchronous nature of modal interactions. ```javascript // Use custom modal instead of browser confirm $.rails.confirm = function(message) { return new Promise(resolve => { showCustomModal(message, resolve); }); }; ``` -------------------------------- ### Correct jQuery-UJS Dependency Order Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Ensure jQuery is loaded before jQuery-UJS in the asset manifest to prevent errors. This example shows the correct order. ```javascript // Correct order //= require jquery3 //= require jquery_ujs // Wrong order (will fail) //= require jquery_ujs //= require jquery3 ``` -------------------------------- ### Source Map Usage in Production Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Source maps are automatically served by browsers when present, allowing debugging of minified code in production. This example shows the HTML for a minified jQuery script. ```html ``` -------------------------------- ### Automatic Initialization Check Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Demonstrates the condition under which jQuery-UJS automatically initializes itself. The `rails:attachBindings` event is fired to trigger setup, including CSRF protection and event binding. ```javascript if (rails.fire($document, 'rails:attachBindings')) { // Automatic setup: // 1. Adds CSRF protection to all AJAX requests // 2. Binds click/change/submit handlers to selector matches // 3. Sets up event delegation } ``` -------------------------------- ### Production Asset Compilation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md During `rails assets:precompile`, assets are minified, fingerprinted, and gzipped for production. This example shows the resulting script tag for jQuery 3. ```html ``` -------------------------------- ### Custom Application JavaScript with jQuery Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Add custom JavaScript code after asset manifest requires. This example shows initializing code within a jQuery ready function. ```javascript // app/assets/javascripts/application.js //= require jquery3 //= require jquery_ujs $(function() { // Your code here console.log('jQuery is ready'); }); // Or in a separate file //= require_tree . ``` -------------------------------- ### Listening to AJAX BeforeSend Event Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md JavaScript code to listen for the `ajax:beforeSend` event, which fires before an AJAX request is sent. This example logs the request URL to the console. ```javascript $(document).on('ajax:beforeSend', function(e, xhr, settings) { console.log('Starting AJAX request to:', settings.url); }); ``` -------------------------------- ### Test ERB with jQuery for View Rendering Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/TESTING_GUIDE.md Example of testing JavaScript generated by ERB templates, specifically how to assert HTML updates and element visibility using jQuery. ```erb # app/views/users/create.js.erb $("#user-form").html("<%= escape_javascript(render 'form') %>"); $("#success-message").show("blind"); ``` ```ruby # test/integration/user_creation_test.rb def test_create_user post users_path, params: { user: { name: 'John' } }, xhr: true assert_select_jquery :html, '#user-form' do assert_select 'form' end assert_select_jquery :show, :blind, '#success-message' end ``` -------------------------------- ### Remote Form with Dynamic Data Loading Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md This example shows a form that uses data attributes to make a remote AJAX request when a customer is selected. The response updates a customer details section. Ensure the controller has a `customer_details` action that renders JSON. ```erb
``` -------------------------------- ### Rails Controller for Customer Details Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md This controller action handles requests for customer details, finding the customer by ID and rendering their information as JSON. This is used by the remote form example. ```ruby # app/controllers/orders_controller.rb class OrdersController < ApplicationController def customer_details @customer = Customer.find(params[:id]) render json: @customer end end ``` -------------------------------- ### Listening to AJAX Success Event Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md JavaScript code to listen for the `ajax:success` event, which fires upon a successful AJAX response. This example logs a success message to the console. ```javascript $(document).on('ajax:success', function(e, data, status, xhr) { console.log('Request succeeded'); }); ``` -------------------------------- ### Link with Multiple Data Attributes Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Use data attributes on links to control method, confirmation, AJAX requests, and button text during submission. This example demonstrates a delete link with confirmation and AJAX submission. ```html Delete ``` -------------------------------- ### Accessing Version Constants in Ruby Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/VERSIONS.md Demonstrates how to require the version file and access all defined version constants within a Ruby environment. ```ruby require 'jquery/rails/version' Jquery::Rails::VERSION # "4.6.1" Jquery::Rails::JQUERY_VERSION # "1.12.4" Jquery::Rails::JQUERY_2_VERSION # "2.2.4" Jquery::Rails::JQUERY_3_VERSION # "3.7.1" Jquery::Rails::JQUERY_UJS_VERSION # "1.2.3" ``` -------------------------------- ### List All Available Assets Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Use the `rails assets:precompile --trace` command to list all assets that are being precompiled. This is useful for debugging the asset pipeline. ```bash # List all available assets rails assets:precompile --trace ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Stage all changes and create a commit with a descriptive log message. ```bash git add ... git commit ``` -------------------------------- ### Fork and Clone Project Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Clone the forked project and set up the upstream remote for future updates. ```bash git clone https://github.com/contributor/jquery-rails.git cd jquery-rails git remote add upstream https://github.com/rails/jquery-rails.git ``` -------------------------------- ### href(element) Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Gets an element's href attribute. This method is overridable for custom link handling. ```APIDOC ## href(element) ### Description Gets an element's href attribute. Overridable for custom link handling. ### Parameters #### Element - **element** (jQuery) - Link element ### Returns String - The element's href attribute ### Example ```javascript var url = $.rails.href($('a.api-link')); ``` ``` -------------------------------- ### Get Element Href Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Retrieve the href attribute of a link element. This function can be overridden for custom link handling. ```javascript var url = $.rails.href($('a.api-link')); ``` -------------------------------- ### Asset Pipeline Manifest Format Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md An alternative way to declare asset dependencies using the manifest format. ```javascript /* *= require jquery3 *= require jquery_ujs *= require_self *= require_tree . */ ``` -------------------------------- ### HTML Data Attributes for Unobtrusive JavaScript Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md Examples of HTML data attributes used by jQuery-UJS for unobtrusive JavaScript interactions. ```html
``` -------------------------------- ### Configure Git User Information Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Set your global Git user name and email address for commit authorship. ```bash git config --global user.name "Your Name" git config --global user.email "contributor@example.com" ``` -------------------------------- ### Create Topic Branch Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Update your local master branch and create a new branch for your feature or bug fix. ```bash git checkout master git pull upstream master git checkout -b my-feature-branch ``` -------------------------------- ### Override AJAX Handler Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md Replaces the default AJAX handling logic with a custom implementation by overriding the `$.rails.ajax` function. This example uses `fetch` for making the AJAX request. ```javascript $.rails.ajax = function(options) { return $.fetch(options.url, { method: options.type, body: options.data }); }; ``` -------------------------------- ### Verify Source Map File Existence Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Confirm that the `jquery3.min.map` source map file exists in the expected location, typically `vendor/assets/javascripts/`. The map file path must correspond to the JavaScript file path. ```bash ls -la vendor/assets/javascripts/jquery3.min.map ``` -------------------------------- ### Listening to AJAX Error Event Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md JavaScript code to listen for the `ajax:error` event, which fires when an AJAX request encounters an error. This example logs the error to the console. ```javascript $(document).on('ajax:error', function(e, xhr, status, error) { console.log('Request failed:', error); }); ``` -------------------------------- ### Test jQuery appendTo() and prependTo() Methods Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/TESTING_GUIDE.md Assert that `appendTo()` or `prependTo()` have been used to add new HTML content to specified elements, verifying the added content. ```ruby def test_add_comment post comments_path(post), params: { comment: { body: 'Great!' } }, xhr: true # Verify appended HTML assert_select_jquery :appendTo, '#comments' do assert_select '.comment', 'Great!' assert_select '.author', 'John' end # Verify prepended HTML assert_select_jquery :prependTo, '#new-comments' do assert_select '.comment' end end ``` -------------------------------- ### Confirmation on File Deletion with data-method and data-confirm Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Combine data-method and data-confirm on a link to perform a DELETE request after user confirmation. The action is prevented if the user cancels the dialog. ```html
Remove File ``` -------------------------------- ### handleMethod(link) Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Handles links with a `data-method` attribute (e.g., DELETE, PUT, PATCH) by creating and submitting a hidden form. ```APIDOC ## handleMethod(link) ### Description Handles links with `data-method` attribute (DELETE, PUT, PATCH). Creates a hidden form and submits it. ### Parameters #### Link - **link** (jQuery) - Link with `data-method` attribute ### HTML Example ```html Delete User ``` ### Process 1. Creates hidden form with POST method. 2. Adds hidden input with `_method=DELETE`. 3. Adds CSRF token if applicable. 4. Submits form to link's href. ### Example ```javascript var deleteLink = $('a[data-method=delete]'); $.rails.handleMethod(deleteLink); // Creates and submits:
// // //
``` ``` -------------------------------- ### Test Observable Behavior in User Creation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/TESTING_GUIDE.md Focuses on testing the user-observable outcome of an action, such as verifying the appearance of new content after user creation. ```ruby def test_user_creation # Test what the user sees/experiences post users_path, params: { user: { name: 'John' } }, xhr: true assert_select_jquery :html, '#user-list' do assert_select '.user-item', 'John' end end ``` -------------------------------- ### Custom Action Button with HTML using data-disable-with Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Use data-disable-with with HTML content to display rich text, like a spinner, while a button is disabled during an action. ```html ``` -------------------------------- ### Delete Link with Confirmation Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md An HTML anchor tag configured for a DELETE request with a confirmation dialog. The `data-confirm` attribute specifies the message shown to the user before the action is allowed. ```html Delete ``` -------------------------------- ### Avoid Testing Implementation Details Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/TESTING_GUIDE.md Contrasts testing specific HTML structures (bad) with testing meaningful content or attributes (good) to ensure tests are robust against minor UI changes. ```ruby # Bad - tests specific HTML structure assert_select_jquery :html, '#user-form' do assert_select 'div > form > input[type=text]:first' end # Good - tests meaningful content assert_select_jquery :html, '#user-form' do assert_select 'input[name="user[name]"]' assert_select 'input[name="user[email]"]' end ``` -------------------------------- ### Configure Browser Caching Headers Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Set browser caching headers in `config/environments/production.rb` to control how long browsers should cache static assets. A `max-age` of 31536000 seconds (1 year) is common. ```ruby config.static_cache_control = "public, max-age=31536000" ``` -------------------------------- ### allowAction Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Handles the `data-confirm` attribute on elements, presenting a confirmation dialog to the user. It fires `confirm` and `confirm:complete` events. ```APIDOC ## allowAction(element) ### Description Handles user confirmation for actions triggered by elements with a `data-confirm` attribute. It fires `confirm` and `confirm:complete` events and returns a boolean indicating user confirmation. ### Method ```javascript allowAction: function(element) ``` ### Parameters #### Path Parameters - **element** (jQuery) - Required - Element with a `data-confirm` attribute. ``` -------------------------------- ### Remote Form Submission Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md An HTML form configured for remote submission using `data-remote="true"`. This enables the form to be submitted via AJAX without a page reload. ```html
``` -------------------------------- ### Check jquery-rails Gem Version in Rails App Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/VERSIONS.md These bash commands help you find the installed version of the jquery-rails gem within your Rails application. Use `gem list` or `bundle show` for verification. ```bash gem list | grep jquery-rails ``` ```bash bundle show jquery-rails ``` -------------------------------- ### Rebase and Force Push Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Rebase your feature branch onto the latest upstream master and force push the changes. ```bash git fetch upstream git rebase upstream/master git push origin my-feature-branch -f ``` -------------------------------- ### Configure Local Gem for Testing Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Modify the Gemfile in a demo Rails app to point to your local jquery-rails gem for testing changes. ```ruby gem 'jquery-rails', :path => '../path/to/jquery-rails' ``` -------------------------------- ### Form with Remote AJAX and JSON Type Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Configure forms for remote AJAX submissions with a specified data type. This example shows a form that submits comments via AJAX and expects JSON in return. ```html
``` -------------------------------- ### Complex Selectors Assertion Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Demonstrates asserting jQuery method calls with complex CSS selectors, including attribute selectors and descendant combinators. Use this to test manipulations on precisely targeted elements. ```javascript // Response: // $("#cart tr:not(.total_line) > *").remove(); // $("[data-placeholder~=name]").remove(); ``` ```ruby assert_select_jquery :remove, "#cart tr:not(.total_line) > *" # ✓ Passes assert_select_jquery :remove, "[data-placeholder~=name]" # ✓ Passes ``` -------------------------------- ### Access Jquery::Rails Version Constants Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md Demonstrates how to access the version constants provided by the Jquery::Rails module in a Rails application. ```ruby # In Rails app Jquery::Rails::VERSION # "4.6.1" Jquery::Rails::JQUERY_VERSION # "1.12.4" ``` -------------------------------- ### jQuery Event Handling for AJAX Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Listen to standard jQuery events triggered by data attributes to manage AJAX request lifecycles. Examples include listening for 'ajax:before', 'ajax:success', 'confirm', and 'ajax:complete'. ```javascript // Listen for any remote element $(document).on('ajax:before', function(e) { console.log('AJAX request starting'); // return false to cancel }); // Listen for specific form $('form#search').on('ajax:success', function(e, data) { console.log('Results:', data); }); // Listen for confirmation $('a.delete').on('confirm', function(e) { e.preventDefault(); // Skip confirmation dialog }); // Listen for completion $('form[data-remote]').on('ajax:complete', function(e, xhr) { hideLoadingSpinner(); }); ``` -------------------------------- ### Multiple Calls in Block Assertion Example Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Asserts multiple jQuery method calls within a block, verifying the count of elements and specific content. This is useful for testing scenarios where multiple items are added or modified. ```javascript // Response: // $("
  • Item 1
  • ").appendTo("#list"); // $("
  • Item 2
  • ").appendTo("#list"); // $("
  • Item 3
  • ").appendTo("#list"); ``` ```ruby assert_select_jquery :appendTo, '#list' do assert_select 'li', count: 3 assert_select 'li', 'Item 1' assert_select 'li', 'Item 2' assert_select 'li', 'Item 3' end ``` -------------------------------- ### Load jQuery from CDN with Fallback Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Configure your application to load jQuery from a CDN, while still using jQuery-UJS from the gem. Ensure the CDN script tag is placed before the application's JavaScript include tag. ```javascript // app/assets/javascripts/application.js //= require jquery_ujs // Don't require jquery; load from CDN instead ``` ```erb <%= javascript_include_tag "application" %> ``` -------------------------------- ### Include Credentials in Cross-Origin AJAX Requests Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Use `data-with-credentials` to enable sending credentials, such as cookies or authorization headers, with cross-origin AJAX requests. This is essential for authenticated requests to external domains. ```html
    Load Files ``` -------------------------------- ### Access Jquery::Rails Constants and Engine Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md Shows how to access version constants and the Engine class from the Jquery::Rails module, and how to include the gem in a Gemfile. ```ruby require 'jquery/rails/version' # All constants accessible via the module Jquery::Rails::VERSION Jquery::Rails::JQUERY_3_VERSION # Or via the Engine Jquery::Rails::Engine # In Gemfile gem 'jquery-rails', '~> 4.6' ``` -------------------------------- ### Rails Controller for User Creation Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md This Rails controller action handles the creation of a new user. It saves the user and renders a JSON response indicating success or failure with validation errors. ```ruby # app/controllers/users_controller.rb class UsersController < ApplicationController def create @user = User.new(user_params) if @user.save render json: { success: true, user: @user } else render json: { success: false, errors: @user.errors.messages }, status: :unprocessable_entity end end private def user_params params.require(:user).permit(:email, :name, :password) end end ``` -------------------------------- ### Update Local Gem and Run RSpec Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md Update the bundled jquery-rails gem to your local version and run the RSpec tests. ```bash bundle update jquery-rails bundle exec rspec spec/ ``` -------------------------------- ### Rails Engine Inheritance Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md Illustrates the inheritance hierarchy for the Jquery::Rails::Engine, showing it inherits from Rails::Engine. ```text ::Rails::Engine (Rails framework base class) ↑ └── Jquery::Rails::Engine ``` -------------------------------- ### Confirmation on Link Click with data-confirm Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md Use data-confirm to display a confirmation dialog before executing an action on a link. The action is prevented if the user cancels the dialog. ```html Delete User ``` -------------------------------- ### Include jQuery 1 (Default) in Manifest Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md Include jQuery 1.x, jQuery-UJS, and all other JavaScript files in the directory using Sprockets directives in application.js. ```javascript //= require jquery //= require jquery_ujs //= require_tree . ``` -------------------------------- ### Testing Integration with assert_select_jquery Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/Rails-Engine.md This code snippet shows how the Engine automatically requires testing utilities in test environments, making assert_select_jquery available. ```ruby # Automatically loaded when Rails.env.test? is true require 'jquery/assert_select' if ::Rails.env.test? ``` -------------------------------- ### Event and Callback System Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md Methods for triggering and handling custom events within the jQuery-UJS adapter, facilitating customization and extension of its behavior. ```APIDOC ## fire(obj, name, data) ### Description Triggers an event on an element and returns whether all handlers allowed it to continue. This is a core method for custom event handling. ### Method `POST` (implicitly, when triggering events) ### Endpoint `$.rails.fire(obj, name, data)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj** (jQuery Element) - The element to trigger the event on. - **name** (String) - The name of the event to trigger. - **data** (Array) - Optional data to pass to the event handlers. ### Returns - **Boolean**: `false` if any handler returned `false`, `true` otherwise. ### Example ```javascript var allowed = $.rails.fire($('a.delete'), 'ajax:before', [data]); if (allowed) { // Proceed with AJAX request } ``` ``` ```APIDOC ## confirm(message) ### Description Shows a confirmation dialog to the user. This method can be overridden to provide custom dialog implementations. ### Method `GET` (implicitly, when showing dialogs) ### Endpoint `$.rails.confirm(message)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (String) - The confirmation message to display to the user. ### Returns - **Boolean**: The user's response (`true` for yes, `false` for no). ### Example ```javascript // Default confirmation if ($.rails.confirm('Are you sure?')) { // User confirmed } // Custom confirmation using Promises $.rails.confirm = function(message) { return new Promise(resolve => { showCustomDialog(message, resolve); }); }; ``` ``` -------------------------------- ### Escaping Selectors for Regex Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md Demonstrates how special regex characters in selectors are escaped for pattern matching. ```ruby escape_id("[id]") # => "\[id\]" ``` ```ruby escape_id(".class") # => "\.class" ``` ```ruby escape_id("#id") # => "#id" (hash not escaped) ``` -------------------------------- ### Automatic Loading of jQuery Rails Gem Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md Demonstrates the automatic loading process of the jQuery Rails gem based on the Rails environment, including conditional loading for test utilities. ```ruby # lib/jquery-rails.rb require 'jquery/rails' require 'jquery/rails/engine' require 'jquery/rails/version' # Conditional test utilities require 'jquery/assert_select' if ::Rails.env.test? ``` -------------------------------- ### jQuery Version Information in JavaScript File Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/VERSIONS.md Shows how version information is embedded as comments within the jQuery JavaScript files. ```javascript // jquery3.js /*! * jQuery JavaScript Library v3.7.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * ... */ ``` -------------------------------- ### Correct Load Order for jQuery and jQuery-UJS Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md Specifies the correct load order for jQuery and jQuery-UJS in `application.js`. jQuery must be required before `jquery_ujs` to ensure proper functionality. ```javascript //= require jquery3 //= require jquery_ujs # Must come after jquery ```