### Command-Line Install for StimulusReflex Source: https://docs.stimulusreflex.com/hello-world/setup This snippet outlines the terminal commands to install StimulusReflex and Stimulus in a Rails project. It automates common file creation, provides an example, and configures caching for development. ```bash # Example commands for installation (actual commands not provided in text) # bundle add stimulus_reflex # rails stimulus_reflex:install ``` -------------------------------- ### Install StimulusReflex from Main Branch (Edge) Source: https://docs.stimulusreflex.com/hello-world/setup Guides on how to install the latest development version of StimulusReflex directly from its main branch on GitHub. This is useful for testing the newest features or bug fixes before they are officially released. ```ruby gem "stimulus_reflex",github:"stimulusreflex/stimulus_reflex",branch:"main" ``` ```bash yarn add stimulus_reflex@https://github.com/stimulusreflex/dev-builds/archive/refs/tags/stimulus_reflex/[commitsha].tar.gz ``` -------------------------------- ### Manual Setup Commands Source: https://docs.stimulusreflex.com/hello-world/setup Commands for manually setting up StimulusReflex, including adding gems, installing the client library, enabling caching, and generating the initializer. ```ruby bundle add stimulus_reflex bundle add redis-session-store yarn add stimulus_reflex rails dev:cache # caching needs to be enabled rails generate stimulus_reflex:initializer ``` -------------------------------- ### Install StimulusReflex (Automatic) Source: https://docs.stimulusreflex.com/hello-world/setup Runs the StimulusReflex installer to automatically detect and configure your JavaScript bundling setup. ```shell rails stimulus_reflex:install ``` -------------------------------- ### Rails 5.2 Support Source: https://docs.stimulusreflex.com/hello-world/setup Information regarding specific support for Rails version 5.2, indicating that a different setup procedure might be required compared to Rails 6+. ```text For Rails 5.2, refer to the specific guide linked here. ``` -------------------------------- ### AnyCable Setup Wizard Source: https://docs.stimulusreflex.com/appendices/deployment Command to run the AnyCable setup wizard after installing the gem, which helps configure AnyCable for your Rails application. ```bash rails g anycable:setup ``` -------------------------------- ### AnyCable Go Installation Source: https://docs.stimulusreflex.com/appendices/deployment Instructions for installing the AnyCable Go server, a key component for replacing the default Ruby WebSocket server. ```APIDOC AnyCable Go Installation: - Download binaries from: https://github.com/anycable/anycable-go/releases - Use Docker images: https://hub.docker.com/repository/docker/anycable/anycable-go/tags?page=1&name=preview ``` -------------------------------- ### StimulusReflex Configuration Notes Source: https://docs.stimulusreflex.com/hello-world/setup Key configuration points for StimulusReflex, including the recommendation to use Redis and how to handle caching in development environments. ```text Recommendation: Use Redis for StimulusReflex. Details on setup without Redis are available separately. Caching is enabled in development environments by default. ``` -------------------------------- ### Stimulus Application Configuration Source: https://docs.stimulusreflex.com/hello-world/setup Basic Stimulus application configuration, setting debug mode and the ActionCable consumer. ```javascript import { Application } from "@hotwired/stimulus" import consumer from "../channels/consumer" const application = Application.start() // Configure Stimulus development experience application.debug = false application.consumer = consumer window.Stimulus = application export { application } ``` -------------------------------- ### StimulusReflex Generator Source: https://docs.stimulusreflex.com/hello-world/quickstart Provides the command to generate a new Reflex class using the StimulusReflex generator. This command scaffolds a new Reflex file, including a basic example of a Reflex method. ```ruby rails generate stimulus_reflex Counter ``` -------------------------------- ### ViewComponent Integration Source: https://docs.stimulusreflex.com/hello-world/setup Notes on integrating StimulusReflex with ViewComponent, a library for building reusable UI components in Rails. ```text Information on ViewComponent integration is available. ``` -------------------------------- ### Polyfills for IE11 Source: https://docs.stimulusreflex.com/hello-world/setup Details on polyfills required for Internet Explorer 11 compatibility with StimulusReflex. ```text Polyfills for IE11 are mentioned as a configuration option. ``` -------------------------------- ### Configure StimulusReflex Version Sanity Checks Source: https://docs.stimulusreflex.com/hello-world/setup Sets the behavior for StimulusReflex when it detects mismatched versions between the gem and npm packages. The `on_failed_sanity_checks` option can be set to `:warn` to only emit a warning instead of preventing the server from starting. ```ruby StimulusReflex.configure do|config| config.on_failed_sanity_checks =:warn end ``` -------------------------------- ### Add StimulusReflex Gem (Manual) Source: https://docs.stimulusreflex.com/hello-world/setup Manually adds the stimulus_reflex gem to your project's Gemfile. ```ruby gem 'stimulus_reflex','~> 3.5' ``` -------------------------------- ### Include ActionCable Meta Tag Source: https://docs.stimulusreflex.com/hello-world/setup Adds the `action_cable_meta_tag` helper to the application's layout file. This allows ActionCable to access necessary configuration settings for real-time communication. ```html <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= action_cable_meta_tag %> ``` -------------------------------- ### Add StimulusReflex Gem (Bundle Add) Source: https://docs.stimulusreflex.com/hello-world/setup Adds the stimulus_reflex gem to your project's Gemfile using the bundle add command. ```shell bundle add stimulus_reflex ``` -------------------------------- ### Configure ActionCable Redis Adapter Source: https://docs.stimulusreflex.com/hello-world/setup Configures the ActionCable adapter to use Redis for development environments. It specifies the Redis URL, channel prefix, and ensures compatibility with environment variables. ```yaml development: adapter:redis url:<%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1"} %> channel_prefix:your_application_development ``` -------------------------------- ### Configure Rack Middleware Source: https://docs.stimulusreflex.com/hello-world/setup Demonstrates how to add custom Rack middleware to StimulusReflex for URL rewriting or other middleware functionalities. This is crucial for compatibility with certain middleware that might interfere with StimulusReflex's Page Morphs. ```ruby StimulusReflex.configure do|config| config.middleware.use FirstRackMiddleware config.middleware.use SecondRackMiddleware end ``` -------------------------------- ### Stimulus Controller Index Configuration Source: https://docs.stimulusreflex.com/hello-world/setup Configures the Stimulus controller index to import and register StimulusReflex, initializing it with the application controller and enabling debug mode. ```javascript import { application } from "./application" import applicationController from "./application_controller" import StimulusReflex from "stimulus_reflex" import controllers from "./**/*_controller.js" controllers.forEach((controller) => { application.register(controller.name, controller.module.default) }) StimulusReflex.initialize(application, { applicationController, isolate: true }) // consider removing these options in production StimulusReflex.debug = true // end remove ``` -------------------------------- ### Development Environment Configuration (Redis) Source: https://docs.stimulusreflex.com/hello-world/setup Configures the Rails development environment to use Redis for caching, which is recommended for StimulusReflex session management. ```ruby Rails.application.configure do # ... other configurations config.cache_store = :redis_cache_store, { url: "redis://localhost:6379/0" } # Example Redis URL # ... other configurations end ``` -------------------------------- ### Trigger Reflex Actions Inside Stimulus Controllers Source: https://docs.stimulusreflex.com/hello-world/quickstart Shows how to initiate StimulusReflex actions from within a Stimulus controller's methods. This allows for more complex logic and integration with existing Stimulus controller functionality. ```javascript import { Controller } from "@hotwired/stimulus" export default class extends Controller { increment() { this.stimulusReflex.perform("Counter#increment") } } ``` -------------------------------- ### StimulusReflex Official AnyCable Documentation Source: https://docs.stimulusreflex.com/appendices/deployment Link to the official AnyCable documentation specifically for StimulusReflex integration. ```APIDOC StimulusReflex AnyCable Docs: - URL: https://docs.anycable.io/v1/#/ruby/stimulus_reflex ``` -------------------------------- ### Configure Redis Cache and Session Stores Source: https://docs.stimulusreflex.com/hello-world/setup Sets up Redis for both cache and session storage in the StimulusReflex configuration. It specifies the Redis URL from environment variables and configures session store options like compression and expiration. ```ruby config.cache_store =:redis_cache_store,{url:ENV.fetch("REDIS_URL"){"redis://localhost:6379/1"}} config.session_store :redis_session_store,key:"_sessions_development",compress:true,pool_size:5,expire_after:1.year ``` -------------------------------- ### AnyCable Rails Gem Installation Source: https://docs.stimulusreflex.com/appendices/deployment Instructions for adding the AnyCable Rails gem to your project's Gemfile for enhanced WebSocket scalability. ```ruby gem "anycable-rails", "~> 1.0" ``` -------------------------------- ### Start Rails Server Source: https://docs.stimulusreflex.com/appendices/no-redis Starts the Rails server after applying the new configurations for a Redis-less StimulusReflex setup. ```shell rails s ``` -------------------------------- ### HTML Structure for StimulusReflex Example Source: https://docs.stimulusreflex.com/guide/morph-modes Provides the HTML structure for a StimulusReflex example, including elements with IDs and data attributes that might be targeted by reflex actions. ```html
Just breathe in... and out.
``` -------------------------------- ### Trigger Reflex Actions with Data Attributes Source: https://docs.stimulusreflex.com/hello-world/quickstart Demonstrates how to trigger StimulusReflex actions directly from HTML elements using the `data-reflex` attribute. This is a fundamental way to connect user interactions to server-side Ruby code. ```html ``` -------------------------------- ### Generic Life-cycle Methods Example Source: https://docs.stimulusreflex.com/guide/lifecycle Demonstrates using generic life-cycle methods like `beforeReflex` to modify DOM elements before a Reflex action is executed. This example updates anchor text based on the Reflex action name. ```html
Eat Poop
``` ```javascript import ApplicationController from'./application_controller.js' export default class extends ApplicationController { beforeReflex(anchorElement) { const { reflex } = anchorElement.dataset if (reflex.match(/masticate$/)) anchorElement.innerText = 'Eating...' if (reflex.match(/defecate$/)) anchorElement.innerText = 'Pooping...' } } ``` -------------------------------- ### ActionCable Connection Setup Source: https://docs.stimulusreflex.com/guide/authentication Defines the `current_user` accessor in the base ActionCable connection class. This accessor will be populated by channel authentication. ```ruby module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user end end ``` -------------------------------- ### StimulusReflex Generator Usage Source: https://docs.stimulusreflex.com/hello-world/quickstart This snippet shows how to use the StimulusReflex generator to scaffold new Reflexes. It demonstrates the command to generate files for a 'user' reflex, including the associated JavaScript controller and Ruby Reflex classes. It also mentions that existing files like `application_controller.js` and `application_reflex.rb` are preserved. ```bash railsgeneratestimulus_reflexuser ``` -------------------------------- ### Add IE11 Polyfills Source: https://docs.stimulusreflex.com/hello-world/setup Shows how to include polyfills for Internet Explorer 11 support using the '@stimulus_reflex/polyfills' package. These should be imported before your Stimulus controllers to ensure older browsers can render correctly. ```javascript // other stuff import'@stimulus_reflex/polyfills' import'controllers' ``` -------------------------------- ### Example Reflex for Scoping Morphs Source: https://docs.stimulusreflex.com/guide/morph-modes A Ruby example demonstrating a StimulusReflex controller that updates `@words` based on input, intended to be used with the `data-reflex-root` attribute for scoped DOM updates. ```ruby class ExampleReflex < ApplicationReflex def words @words = element[:value] end end ``` -------------------------------- ### Rails 5.2+ Action Cable Integration Source: https://docs.stimulusreflex.com/hello-world/setup Instructions for integrating StimulusReflex with Rails 5.2+ by updating the Action Cable package. This involves replacing the older 'actioncable' with '@rails/actioncable' and adjusting import statements for compatibility. ```javascript // other stuff import'@stimulus_reflex/polyfills' import'controllers' ``` -------------------------------- ### AnyCable Cache Store Configuration Source: https://docs.stimulusreflex.com/appendices/deployment Guidance on selecting a compatible cache store when using AnyCable, specifically advising against MemoryStore. ```APIDOC AnyCable Cache Store: - Requirement: Must select a cache store other than MemoryStore. - Reason: MemoryStore is not compatible with AnyCable. - Example Compatible Stores: Redis, Memcached, etc. (specific configuration depends on Rails setup) ``` -------------------------------- ### AnyCable Authentication with Devise Source: https://docs.stimulusreflex.com/appendices/deployment References for configuring AnyCable connections with Devise for authentication, including documentation and discussion links. ```APIDOC AnyCable Devise Authentication: - Documentation: https://docs.anycable.io/v1/#/ruby/authentication - Discussion: https://github.com/anycable/anycable-rails/issues/127 ``` -------------------------------- ### Example HTML Structure Source: https://docs.stimulusreflex.com/guide/morph-modes Demonstrates the initial HTML structure including a header with a StimulusReflex data attribute and a partial render for a message. ```html
<%= render partial: "path/to/foo", locals: { message: "Am I the medium or the massage?" } %>
``` -------------------------------- ### Delegate current_user to Connection (ExampleReflex) Source: https://docs.stimulusreflex.com/guide/authentication Delegates the `current_user` method to the ActionCable connection in an ExampleReflex. ```ruby class ExampleReflex < ApplicationReflex delegate :current_user, to: :connection end ``` -------------------------------- ### StimulusReflex Initialization Source: https://docs.stimulusreflex.com/guide/authentication Initializes StimulusReflex with application definitions and connection parameters. ```javascript application.load(definitionsFromContext(context)) StimulusReflex.initialize(application,{ params }) ``` -------------------------------- ### StimulusReflex AnyCable Issue Reporting Source: https://docs.stimulusreflex.com/appendices/deployment Link to report issues related to AnyCable support within the StimulusReflex project. ```APIDOC Report AnyCable Issues: - GitHub Issues: https://github.com/stimulusreflex/stimulus_reflex/issues/46 ``` -------------------------------- ### StimulusReflex Configuration Options Source: https://docs.stimulusreflex.com/appendices/deployment Details various configuration options available for StimulusReflex, including settings for session storage, WebSocket connections, and integration with other libraries. ```APIDOC StimulusReflex: # Configuration options # session_store: Specifies the session store (e.g., :redis_store, :cache_store) # - Default: :cookie_store # - Example: config.session_store :redis_store, url: ENV.fetch("REDIS_URL") # websocket_url: The URL for ActionCable WebSocket connections. # - Default: nil (uses ActionCable.createConsumer()) # - Example: StimulusReflex.config.websocket_url = "wss://your-websocket-host.com/cable" # morph_mode: The default morph mode for elements. # - Options: :html, :attributes, :children, :none # - Default: :html # parent_selector: The CSS selector for the parent element to morph into. # - Default: "body" # ... other configuration options ... ``` -------------------------------- ### Custom Life-cycle Methods Example Source: https://docs.stimulusreflex.com/guide/lifecycle Illustrates custom life-cycle methods that are specific to Reflex actions, such as `beforePoke` and `beforePurge`. These methods allow for more granular control over the callback behavior for each action. ```html
Poke Purge
``` ```javascript import ApplicationController from'./application_controller.js' export default class extends ApplicationController { beforePoke(element) { element.innerText = 'Poking...' } beforePurge(element) { element.innerText = 'Purging...' } } ``` -------------------------------- ### Trigger Reflex Action with Stimulus Controller Source: https://docs.stimulusreflex.com/hello-world/quickstart This snippet demonstrates how to trigger a StimulusReflex action from a Stimulus controller. It includes the necessary HTML data attributes, the JavaScript controller logic using `this.stimulate()`, and the corresponding Ruby Reflex class to handle the action. It also shows how to pass arguments to the Reflex action and use the Rails session for persistence. ```html Increment <%= @count %> ``` ```javascript import ApplicationController from'./application_controller.js' exportdefaultclassextendsApplicationController{ increment(event){ event.preventDefault() this.stimulate('Counter#increment',1) } } ``` ```ruby classCounterReflex<%= Rails.cache.fetch("fortune") { `fortune | cowsay` } %> ``` -------------------------------- ### Redis Adapter for Development Source: https://docs.stimulusreflex.com/appendices/troubleshooting For development mode, you must install and configure Redis as the adapter in your `config/cable.yml` file. ```yaml development: adapter: redis url: redis://localhost:6379/1 test: adapter: async production: adapter: redis url: redis://localhost:6379/1 ``` -------------------------------- ### Server-Side Reflex Callbacks (Ruby) Source: https://docs.stimulusreflex.com/guide/lifecycle Demonstrates how to use server-side callbacks in StimulusReflex to control Reflex actions. Includes examples for `before_reflex`, `around_reflex`, and `after_reflex` with conditional logic (`if`, `unless`, `only`, `except`), blocks, multiple method calls, and halting execution. ```ruby class ExampleReflex < ApplicationReflex # will run only if the element has the step attribute, can use "unless" instead of "if" for opposite condition before_reflex :do_stuff, if: proc { |reflex| reflex.element.dataset.step } # will run only if the reflex instance has a url attribute, can use "unless" instead of "if" for opposite condition before_reflex :do_stuff, if: :url # will run before all reflexes before_reflex :do_stuff # will run before increment reflex, can use "except" instead of "only" for opposite condition before_reflex :do_stuff, only: [:increment] # will run around all reflexes, must have a yield in the callback around_reflex :do_stuff_around # will run after all reflexes after_reflex :do_stuff # Example with a block before_reflex do # callback logic end # Example with multiple method names before_reflex :do_stuff, :do_stuff2 # Example with halt before_reflex :run_checks def increment # reflex logic end def decrement # reflex logic end private def run_checks throw :abort # this will prevent the Reflex from continuing end def do_stuff # callback logic end def do_stuff2 # callback logic end def do_stuff_around # before yield # after end end ``` -------------------------------- ### HTML Input for StimulusReflex Example Source: https://docs.stimulusreflex.com/guide/reflex-classes An example HTML input element configured with StimulusReflex attributes, demonstrating how to trigger a Reflex action and pass data. This includes `data-reflex` for specifying the target controller and method, and custom `data-*` attributes for passing values. ```html ``` -------------------------------- ### Turbolinks / Turbo Drive Integration Source: https://docs.stimulusreflex.com/appendices/deployment Recommendation and explanation of using Turbolinks 5 or Turbo Drive with StimulusReflex for performance benefits and reduced resource consumption. ```javascript // Ensure a single, memoized consumer.js is used across all channels // This allows the ActionCable connection to persist between page loads when using Turbolinks/Turbo Drive. ``` -------------------------------- ### Counter Reflex Implementation Source: https://docs.stimulusreflex.com/hello-world/quickstart This Ruby code defines a StimulusReflex class `CounterReflex` with an `increment` action. This action is triggered by the client-side `data-reflex` attribute, reads data attributes from the element, updates an instance variable `@count`, and prepares it for re-rendering. ```ruby class CounterReflex < ApplicationReflex def increment @count = element.dataset.count.to_i + element.dataset.step.to_i end end ``` -------------------------------- ### StimulusReflex Multi-Tenant Applications Source: https://docs.stimulusreflex.com/guide/authentication Addresses considerations for building multi-tenant applications with StimulusReflex, ensuring data isolation and proper user context. ```APIDOC Multi-Tenant Applications: - StimulusReflex requires careful configuration for multi-tenant environments. - Ensure that user sessions and data are correctly scoped to their respective tenants. - This often involves setting a `current_tenant` or similar identifier within the connection or Reflex context. - Example: In your ActionCable connection, set the tenant based on the authenticated user's association. ``` -------------------------------- ### Add Redis Gem Source: https://docs.stimulusreflex.com/appendices/deployment Enables the 'redis' gem for use in the application, specifying a minimum version and requiring it. ```ruby gem "redis", ">= 4.0", require: ["redis"] ``` -------------------------------- ### Install Redis Gem Source: https://docs.stimulusreflex.com/appendices/testing Adds the Redis gem to your Gemfile for Redis connectivity. Ensure Redis is installed and running. ```ruby gem "redis",">= 4.0",require:["redis"] ``` -------------------------------- ### Trigger Reflex with data-reflex Attribute Source: https://docs.stimulusreflex.com/hello-world/quickstart This snippet shows how to use the `data-reflex` attribute in an HTML anchor tag to trigger a server-side Reflex action on a click event. It maps a client-side DOM event to a specific Reflex class and action, and passes data to the server via data attributes. ```html Increment <%= @count.to_i %> ``` -------------------------------- ### Configure Production Session Store with Redis Source: https://docs.stimulusreflex.com/appendices/deployment Configures the session store to use 'redis-session-store' in the production environment, specifying serializer, expiration, and Redis connection details. ```ruby config.cache_store = :redis_cache_store,{ url: ENV.fetch("REDIS_URL") } config.session_store( :redis_session_store, key: "_session_production", serializer: ::json, redis: { expire_after: 1.year, ttl: 1.year, key_prefix: "app:session:", url: ENV.fetch("HEROKU_REDIS_MAROON_URL") } ) ``` -------------------------------- ### ActiveRecord, Redis, and Kredis for Persistence Source: https://docs.stimulusreflex.com/guide/persistence Covers the use of ActiveRecord models, Redis, and Kredis within StimulusReflex applications for robust data persistence and state management. ```APIDOC Feature: Data Persistence with ActiveRecord, Redis, and Kredis Description: StimulusReflex applications can leverage common Ruby on Rails persistence layers, including ActiveRecord, Redis, and Kredis, to manage application data. ActiveRecord: - Use standard ActiveRecord models to interact with your database for persistent data storage. - Example: ```ruby class PostReflex < ApplicationReflex def create_post Post.create(title: params[:title], body: params[:body]) end end ``` Redis: - Integrate directly with Redis for caching, real-time data, or as a primary data store, often used with libraries like `redis-rb`. - Example (using `redis-rb`): ```ruby require 'redis' class RealtimeReflex < ApplicationReflex def update_status redis = Redis.new redis.publish('status_channel', { user_id: connection.current_user.id, status: 'online' }.to_json) end end ``` Kredis: - Utilize Kredis, a Ruby client for Redis, which provides a higher-level API for common Redis data structures and operations. - Example: ```ruby class CounterReflex < ApplicationReflex def increment_counter Kredis.increment('page_views') end def get_counter_value @view_count = Kredis.get('page_views') end end ``` Integration Notes: - Ensure Redis is properly configured and running if using it directly or via Kredis. - ActiveRecord persistence follows standard Rails conventions. ``` -------------------------------- ### Stimulus Controller Initialization Source: https://docs.stimulusreflex.com/guide/authentication Initializes the Stimulus application and retrieves the JWT token from the meta tag to pass as a parameter during channel subscription. ```javascript import { Application } from'stimulus' import { definitionsFromContext } from'stimulus/webpack-helpers' import StimulusReflex from'stimulus_reflex' const application = Application.start() const context = require.context('controllers', true, /_controller\.js$/) const params = {token: document.head.querySelector('meta[name=action-cable-auth-token]').content } application.load(definitionsFromContext(context)) ``` -------------------------------- ### Initiating a 'Nothing Morph' Source: https://docs.stimulusreflex.com/guide/morph-modes Shows the syntax for initiating a 'Nothing Morph' in StimulusReflex, which performs server-side actions without directly manipulating the DOM. ```ruby morph :nothing ``` -------------------------------- ### Passing Params to ActionCable Source: https://docs.stimulusreflex.com/guide/authentication Details how to pass custom parameters to ActionCable when establishing a StimulusReflex connection, which can be useful for authentication or context. ```APIDOC Passing params to ActionCable: - Custom parameters can be passed during the ActionCable connection establishment. - This is typically done via the `connection_params` option when initializing StimulusReflex. - Example (JavaScript): `StimulusReflex.consumer.connect('/cable', { websocket: new WebSocket(url, protocols), connection_params: { user_id: 123, session_token: 'abc' } });` - These parameters are then available in the Rails ActionCable connection class. ``` -------------------------------- ### StimulusReflex Authorization Source: https://docs.stimulusreflex.com/guide/authentication Explains how to implement authorization within StimulusReflex using popular Ruby authorization libraries like CanCanCan and Pundit. ```APIDOC Authorization: CanCanCan: - Integration with the CanCanCan authorization gem. - Use `can?` and `cannot?` helpers within Reflexes to check permissions. - Example: `if can?(:edit, @post) # Allow editing end` Pundit: - Integration with the Pundit authorization gem. - Use `policy_scope` and `authorize` within Reflexes. - Example: `authorize @post, :edit? # Allow editing ``` -------------------------------- ### StimulusReflex Instance Variables Source: https://docs.stimulusreflex.com/guide/persistence Details the use of instance variables within StimulusReflex, specifically the `@stimulus_reflex` variable, for managing state and interacting with the Reflex lifecycle. ```APIDOC Feature: Instance Variables in StimulusReflex Description: Instance variables are used within StimulusReflex controllers to maintain state across requests and manage the lifecycle of a Reflex. Key Variable: - `@stimulus_reflex`: A special instance variable provided by the StimulusReflex gem. It offers access to various utilities and information related to the current Reflex. Usage: - Accessing request details. - Interacting with the WebSocket connection. - Managing internal Reflex state. Example (Conceptual): class MyReflex < ApplicationReflex def perform_action # Accessing the stimulus_reflex instance variable current_user = @stimulus_reflex.current_user # ... perform actions using current_user ... end end ``` -------------------------------- ### StimulusReflex Deployment on Render Source: https://docs.stimulusreflex.com/appendices/deployment Provides guidance on deploying StimulusReflex applications to the Render platform. This typically involves setting up environment variables and ensuring correct build pack configurations. ```bash # Example Render configuration (conceptual) # Ensure REDIS_URL is set in Render environment variables if using Redis ``` -------------------------------- ### StimulusReflex Declarative Mapping Source: https://docs.stimulusreflex.com/guide/reflex-classes Illustrates how to declaratively map a click event on an HTML element to a specific Reflex action method (`test`) in a Reflex class (`Example`). ```html ``` -------------------------------- ### Render Deployment - Rack Gem Configuration Source: https://docs.stimulusreflex.com/appendices/deployment Specifies how to configure the Rack gem in the Gemfile to ensure compatibility with ActionCable's websocket connections on Render, addressing potential issues with the X-Forwarded-Proto header. ```ruby gem "rack",git:"https://github.com/rack/rack.git",ref:"8be612a" ``` -------------------------------- ### Example Foo Partial Source: https://docs.stimulusreflex.com/guide/morph-modes The 'foo' partial containing a div with a span that displays a message, intended to be targeted by StimulusReflex. ```html
<%= message %>
``` -------------------------------- ### Native Mobile Wrappers for StimulusReflex Source: https://docs.stimulusreflex.com/appendices/deployment Information on using native mobile wrappers with StimulusReflex, referencing both older Turbolinks-based wrappers and newer Turbo Drive wrappers for iOS and Android. ```APIDOC Native Mobile Wrappers: - Turbolinks iOS (Deprecated): https://github.com/turbolinks/turbolinks-ios - Turbo Drive iOS (Beta): https://github.com/hotwired/turbo-ios - Turbo Drive Android (Beta): https://github.com/hotwired/turbo-android - Example Presentation: https://dev.to/julianrubisch/twitter-clone-with-stimulusreflex-gone-hybrid-native-app-17fm ``` -------------------------------- ### StimulusReflex Example Reflex Source: https://docs.stimulusreflex.com/guide/morph-modes A Ruby class inheriting from ApplicationReflex that defines a 'change' method to perform a selector morph on the '#foo' element. ```ruby class ExampleReflex < ApplicationReflex def change morph "#foo", "Your muscles... they are so tight." end end ``` -------------------------------- ### Pagy Pagination Setup Source: https://docs.stimulusreflex.com/guide/morph-modes Initializes pagination with the Pagy gem in a Rails controller. It sets up the paginated posts and the pagy object for use in the view. ```ruby def index @pagy, @posts = pagy(Post.all, page: 1) end ``` -------------------------------- ### StimulusReflex Architecture Overview Source: https://docs.stimulusreflex.com/hello-world Explains the core components and data flow of StimulusReflex. It details how user interactions are captured, sent to Rails via websockets, processed by Reflex actions, and how CableReady delivers UI updates through morphing. ```APIDOC StimulusReflex Architecture: User Interaction -> StimulusReflex -> Websocket -> Rails Controller -> Reflex Action -> CableReady -> Websocket -> Client -> Morphdom -> UI Update Key Components: - Stimulus: JavaScript framework for connecting to DOM elements. - StimulusReflex: Ruby gem that intercepts user interactions and manages websocket communication. - Rails: Backend framework for processing actions and rendering views. - CableReady: Gem for sending rich data over websockets to the client. - Morphdom: JavaScript library for efficient DOM diffing and patching. Benefits: - Fast UI updates (20-30ms). - No flicker or page reloads. - Eliminates complexity of full-stack frontend frameworks. - Enables small teams to build high-performance reactive UIs. ``` -------------------------------- ### Explicit Policy Validation in StimulusReflex Source: https://docs.stimulusreflex.com/guide/authentication Demonstrates how to use Pundit for explicit policy validation within a StimulusReflex. It shows how to deny a reflex before it starts and how to handle the 'halted' lifecycle event in a Stimulus controller. ```ruby class ExampleReflexPolicy < ApplicationPolicy def test? user.admin? end end ``` ```ruby class ExampleReflex < ApplicationReflex delegate :current_user, to: :connection before_reflex do unless ExampleReflexPolicy.new(current_user, self).test? puts "DENIED" throw :abort end end def test puts "We are authorized!" end end ``` -------------------------------- ### Provision Heroku Redis Addon (Premium Tier, Redis 5) Source: https://docs.stimulusreflex.com/appendices/deployment Command to create a Heroku Redis addon instance with the premium tier, specifically forcing the use of Redis version 5 to ensure compatibility with the 'hiredis' gem. ```bash heroku addons:createheroku-redis:premium-0--version5 ``` -------------------------------- ### Configure ActionCable for External Host Source: https://docs.stimulusreflex.com/appendices/deployment This snippet shows how to configure Rails routes to mount ActionCable and how to update the JavaScript consumer to connect to a different host, including secure WebSocket connections. ```ruby Rails.application.routes.draw do mount ActionCable.server =>'/cable' end ``` ```javascript import{createConsumer}from'@rails/actioncable' exportdefaultcreateConsumer('wss://myapp.com/cable') ``` ```ruby Rails.application.configure do config.action_cable.allowed_request_origins config.action_cable.url ='wss://myapp.com/cable' config.action_cable.disable_request_forgery_protection =true# only if necessary end ``` -------------------------------- ### Morph Container with New Element and Selector Change Source: https://docs.stimulusreflex.com/guide/morph-modes Demonstrates morphing a container where the target element's ID is changed. This example highlights how StimulusReflex handles updates when the CSS selector of the content changes. ```ruby morph "#foo",%(
Just breathe in... and out.
) ``` -------------------------------- ### Enable StimulusReflex Tab Isolation Source: https://docs.stimulusreflex.com/hello-world/setup Initializes StimulusReflex with the `isolate: true` option, enabling tab isolation mode. This ensures that Morph operations are restricted to the active tab, preventing unintended updates across multiple tabs. ```javascript StimulusReflex.initialize(application,{ consumer, controller,isolate:true}) ``` -------------------------------- ### Connecting ActionCable to a Different Host Source: https://docs.stimulusreflex.com/appendices/deployment Illustrates how to configure StimulusReflex to connect ActionCable to a different host, which is often necessary in complex deployment scenarios or when using external WebSocket servers. ```javascript import consumer from "./consumer" consumer.connect("wss://your-websocket-host.com/cable", { // connection options }); ``` -------------------------------- ### Configure Development Cache Store with Redis Source: https://docs.stimulusreflex.com/appendices/deployment Sets the cache store to use Redis in the development environment, specifying the Redis URL and configuring session store behavior. ```ruby config.cache_store = :redis_cache_store,{ url: ENV.fetch("REDIS_URL"){"redis://localhost:6379/1"} } config.session_store( :cache_store, key: "_session_development", compress: true, pool_size: 5, expire_after: 1.year ) ``` -------------------------------- ### Auto-saving Posts with Nested Comments Source: https://docs.stimulusreflex.com/guide/working-with-forms Provides an example of StimulusReflex form handling for an edit action with nested comments. It includes ActiveRecord models, controller setup for memoizing resources, form markup using signed global IDs, and the corresponding Reflex class configuration. ```ruby classPostPostReflex#submit",signed_id:@post.to_sgid.to_s}do|form|%> <%if@post.errors.any?%> <% end %>
<%= form.label :name %> <%= form.text_field :name, data: { reflex: "change->PostReflex#submit", reflex_dataset: "combined"} %>
<%= form.fields_for :comments,@post.comments do|comment_form|%> <%= comment_form.hidden :id %> <%= comment_form.label :name %> <%= comment_form.text_field :name,data:{reflex:"change->PostReflex#submit",reflex_dataset:"combined"}%> <% end %> <%= link_to "New comment","#",data:{reflex:"click->PostReflex#build_comment"}%> <%= form.submit %> <% end %> ``` ```ruby classPostReflex event#keydown"> ``` -------------------------------- ### Nginx + Passenger Configuration for ActionCable Source: https://docs.stimulusreflex.com/appendices/deployment Provides essential Nginx configuration snippets for Passenger deployments to handle secure websocket traffic for ActionCable. It highlights the need to configure the port 443 section for optimal performance. ```nginx server { listen 443; passenger_enabled on; location /cable { passenger_app_group_name YOUR_APP_HERE_action_cable; passenger_force_max_concurrent_requests_per_process 0; } } ```