### Complete Example of Listen Gem Usage Source: https://github.com/guard/listen/blob/master/README.md This example demonstrates how to use the listen gem to monitor a directory and receive callbacks for file modifications, additions, and removals. The listener starts in a separate thread and does not block the main process. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts(modified: modified, added: added, removed: removed) end listener.start sleep ``` -------------------------------- ### CLI Usage - Example Output Source: https://context7.com/guard/listen/llms.txt Example output when using the Listen CLI in verbose mode, showing file additions, modifications, and deletions. ```bash # Starting listen... # + ["/srv/app/new_file.rb"] # > ["/srv/app/modified.rb"] # - ["/srv/app/deleted.rb"] ``` -------------------------------- ### Simplified Bundler and Sass Example Gemfile Source: https://github.com/guard/listen/blob/master/README.md Example Gemfile content for projects using both Listen and Sass, ensuring proper dependency management. ```ruby source 'https://rubygems.org' gem 'listen' gem 'sass' ``` -------------------------------- ### Install listen Gem with Bundler Source: https://github.com/guard/listen/blob/master/README.md Add the listen gem to your Gemfile to install it using Bundler. ```ruby gem 'listen' ``` -------------------------------- ### Basic File Listener Setup Source: https://context7.com/guard/listen/llms.txt Set up a listener for a directory and define a callback block to handle file changes. The listener automatically selects the best available adapter for the operating system. Use `LISTEN_GEM_DEBUGGING=info` to see adapter selection in logs. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Detected #{modified.length} modifications" end listener.start sleep ``` -------------------------------- ### Start Listener Monitoring with Listener#start Source: https://context7.com/guard/listen/llms.txt Starts the listener thread in a non-blocking manner. Use a loop or `sleep` to keep the main process alive and monitor the listener's state. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Files changed: #{modified.length + added.length + removed.length}" end # Start listening (non-blocking) listener.start # Check listener state puts listener.processing? # => true puts listener.paused? # => false puts listener.stopped? # => false # Keep the main process running loop do sleep 1 puts "Still watching..." if listener.processing? end ``` -------------------------------- ### Listener#start - Start Monitoring Source: https://context7.com/guard/listen/llms.txt Starts the listener thread to begin processing file system events. This method is non-blocking and returns immediately after spawning the background thread. ```APIDOC ## Listener#start - Start Monitoring ### Description Starts the listener thread to begin processing file system events. This method is non-blocking. ### Method listener.start ### Parameters None ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Files changed: #{modified.length + added.length + removed.length}" end listener.start puts listener.processing? # => true puts listener.paused? # => false puts listener.stopped? # => false loop do sleep 1 puts "Still watching..." if listener.processing? end ``` ### Response #### Success Response (200) Starts the listener thread. #### Response Example ```ruby # Listener thread started ``` ``` -------------------------------- ### Production-Ready File Watcher with Logging and Signal Handling Source: https://context7.com/guard/listen/llms.txt A comprehensive example demonstrating a robust file watcher with proper error handling, logging, and graceful shutdown. It includes custom handlers for file modifications, additions, and removals, and integrates with the system's logger. ```ruby require 'listen' require 'logger' class FileWatcher def initialize(directories, options = {}) @directories = Array(directories) @options = { only: options[:only] || /\.(rb|erb|haml|slim)$/, ignore: options[:ignore] || [%r{/tmp/}, %r{/log/}, /\.git/], latency: options[:latency] || 0.25, wait_for_delay: options[:wait_for_delay] || 0.1, relative: options[:relative] || false } setup_logging setup_listener setup_signal_handlers end def start @logger.info "Starting file watcher for: #{@directories.join(', ')}" @listener.start loop do sleep 1 break unless @listener.processing? end end def stop @logger.info "Stopping file watcher..." @listener.stop end private def setup_logging @logger = Logger.new(STDOUT) @logger.level = ENV['DEBUG'] ? Logger::DEBUG : Logger::INFO Listen.logger = @logger end def setup_listener @listener = Listen.to(*@directories, **@options) do |modified, added, removed| handle_changes(modified, added, removed) end end def setup_signal_handlers %w[INT TERM].each do |signal| Signal.trap(signal) { stop; exit } end end def handle_changes(modified, added, removed) timestamp = Time.now.strftime('%H:%M:%S') modified.each do |file| @logger.info "[#{timestamp}] Modified: #{file}" on_file_modified(file) end added.each do |file| @logger.info "[#{timestamp}] Added: #{file}" on_file_added(file) end removed.each do |file| @logger.info "[#{timestamp}] Removed: #{file}" on_file_removed(file) end end def on_file_modified(file) # Custom handler - e.g., trigger test run, reload server system("bundle exec rspec #{file}") if file.end_with?('_spec.rb') end def on_file_added(file) # Custom handler for new files end def on_file_removed(file) # Custom handler for deleted files end end # Usage watcher = FileWatcher.new( ['/srv/app', '/srv/lib', '/srv/spec'], only: /\.(rb|rake)$/, ignore: [/vendor/, /coverage/], relative: true ) watcher.start ``` -------------------------------- ### Listen Gem Usage with Multiple Directories Source: https://github.com/guard/listen/blob/master/README.md This example shows how to configure the listen gem to monitor multiple directories simultaneously. The callback block receives arrays of modified, added, and removed file paths. ```ruby listener = Listen.to('dir/to/listen', 'dir/to/listen2') do |modified, added, removed| puts "modified absolute path array: #{modified}" puts "added absolute path array: #{added}" puts "removed absolute path array: #{removed}" end listener.start # starts a listener thread--does not block # do whatever you want here...just don't exit the process :) sleep ``` -------------------------------- ### Listen Gem Debugging Output Example Source: https://github.com/guard/listen/blob/master/README.md This output indicates the time taken to build a record, which is part of the Listen gem's diagnostic mode. It helps verify that the core functionality is working. ```log INFO -- : Record.build(): 0.06773114204406738 seconds ``` -------------------------------- ### Control Listener State Source: https://github.com/guard/listen/blob/master/README.md Demonstrates how to start, pause, resume, and stop a file system listener. Paused listeners collect changes but do not process them. ```ruby listener = Listen.to('dir/path/to/listen') { |modified, added, removed| puts 'handle changes here...' } listener.start listener.paused? # => false listener.processing? # => true listener.pause # stops processing changes (but keeps on collecting them) listener.paused? # => true listener.processing? # => false listener.start # resumes processing changes listener.stop # stop both listening to changes and processing them ``` -------------------------------- ### Listen to Specific Files Source: https://github.com/guard/listen/blob/master/README.md Demonstrates how to configure a listener to only watch specific file types using the `only` option. The `only` option can be updated after the listener has started. ```ruby listener = Listen.to('dir/path/to/listen', only: /\.rb$/) { |modified, added, removed| # ... } listener.start listener.only /_spec\.rb$/ # overwrite all existing only patterns. sleep ``` -------------------------------- ### Create a File System Listener with Listen.to Source: https://context7.com/guard/listen/llms.txt Use Listen.to to create a listener for one or more directories. The block callback receives arrays of modified, added, and removed file paths. Ensure the main thread stays alive using `sleep` or a loop after starting the listener. ```ruby require 'listen' # Basic usage: watch a single directory listener = Listen.to('/path/to/project') do |modified, added, removed| puts "Modified files: #{modified}" # => ["/path/to/project/app.rb"] puts "Added files: #{added}" # => ["/path/to/project/new_file.rb"] puts "Removed files: #{removed}" # => ["/path/to/project/deleted.rb"] end listener.start # starts listener thread (non-blocking) sleep # keep main thread alive ``` ```ruby # Watch multiple directories listener = Listen.to('/srv/app', '/srv/config', '/srv/lib') do |modified, added, removed| modified.each { |file| puts "Changed: #{file}" } added.each { |file| puts "New file: #{file}" } removed.each { |file| puts "Deleted: #{file}" } end listener.start ``` -------------------------------- ### CLI Usage - Help Source: https://context7.com/guard/listen/llms.txt Display all available options for the Listen CLI. ```bash $ listen --help ``` -------------------------------- ### Adapter Selection - Platform-Specific Backends Source: https://context7.com/guard/listen/llms.txt Listen automatically selects the best adapter for your platform. Configure additional adapters via Gemfile for non-default platforms. ```APIDOC ## Adapter Selection - Platform-Specific Backends ### Description Listen automatically selects the best adapter for your platform. Configure additional adapters via Gemfile for non-default platforms. ### Method Automatic selection, configurable via Gemfile. ### Endpoint N/A ### Parameters None ### Request Example ```ruby # Gemfile configuration for different platforms # For Windows - recommended for better performance gem 'wdm', '>= 0.1.0', platforms: [:mingw, :mswin, :x64_mingw] ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### CLI Usage - Command Line Interface Source: https://context7.com/guard/listen/llms.txt Listen provides a command-line binary for quick file watching from the terminal. ```APIDOC ## CLI Usage - Command Line Interface ### Description Listen provides a command-line binary for quick file watching from the terminal. ### Method `listen` command ### Endpoint N/A (Command line tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash # Basic usage - watch current directory $ listen # Watch specific directories $ listen -d /path/to/app /path/to/config # Verbose output (show all changes) $ listen -v -d /srv/app # Use relative paths $ listen -r -d /srv/app # All CLI options $ listen --help # Options: # -v, [--verbose] # Verbose mode # -d, [--directory=DIRECTORY] # One or more directories to listen to # -r, [--relative] # Convert paths relative to current directory # Example output (verbose mode): # Starting listen... # + ["/srv/app/new_file.rb"] # > ["/srv/app/modified.rb"] # - ["/srv/app/deleted.rb"] ``` ### Response Terminal output showing file changes or help information. #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listen.to - Create a File System Listener Source: https://context7.com/guard/listen/llms.txt The primary entry point for creating a new listener. Accepts one or more directory paths and a block callback that receives arrays of modified, added, and removed file paths. ```APIDOC ## Listen.to - Create a File System Listener ### Description Creates a new file system listener that watches specified directories for changes. ### Method Listen.to ### Parameters #### Path Parameters - **directories** (string | Array) - Required - One or more directory paths to watch. - **options** (Hash) - Optional - Configuration options for the listener. - **callback** (Proc) - Required - A block that receives three arrays: modified, added, and removed file paths. ### Request Example ```ruby require 'listen' listener = Listen.to('/path/to/project') do |modified, added, removed| puts "Modified files: #{modified}" puts "Added files: #{added}" puts "Removed files: #{removed}" end listener.start sleep ``` ### Response #### Success Response (200) Returns a Listener object. #### Response Example ```ruby # Listener object instance ``` ``` -------------------------------- ### Adapter Selection - Windows Gemfile Configuration Source: https://context7.com/guard/listen/llms.txt Configure the 'wdm' gem in your Gemfile for Windows platforms to improve Listen's performance. ```ruby # Gemfile configuration for different platforms # For Windows - recommended for better performance gem 'wdm', '>= 0.1.0', platforms: [:mingw, :mswin, :x64_mingw] ``` -------------------------------- ### Configure Listener Options with Listen.to Source: https://context7.com/guard/listen/llms.txt Customize listener behavior by passing an options hash after directory paths. Options include ignore patterns, only patterns, latency, wait delay, polling mode, and relative path output. ```ruby require 'listen' # All available options listener = Listen.to('/srv/app', # Ignore patterns (regexp, evaluated against relative paths) ignore: [%r{/tmp/}, /\.pid$/, /\.log$/], # Override default ignores entirely # ignore!: %r{/custom_ignore/}, # Only watch specific file patterns (regexp, relative file paths) only: /\.(rb|erb|haml)$/, # Delay between checking for changes (seconds) latency: 0.5, # default: 0.25 (1.0 for polling) # Delay between callback invocations when changes exist wait_for_delay: 4, # default: 0.10 # Force polling adapter instead of OS-native force_polling: true, # Return relative paths instead of absolute relative: true, # Custom polling fallback message (or false to disable) polling_fallback_message: 'Using polling mode for file changes.' ) do |modified, added, removed| puts "Changes detected!" end listener.start sleep ``` -------------------------------- ### Add WDM Adapter Gem to Gemfile Source: https://github.com/guard/listen/blob/master/README.md For Windows users, add the 'wdm' gem to your Gemfile for recommended adapter support instead of polling. ```ruby gem 'wdm', '>= 0.1.0' ``` -------------------------------- ### Ignore Files and Extensions Source: https://github.com/guard/listen/blob/master/README.md Shows how to configure a listener to ignore specific files or extensions using the `ignore` and `ignore!` options. `ignore!` overwrites existing patterns, while `ignore` adds to them. ```ruby listener = Listen.to('dir/path/to/listen', ignore: /\.txt/) { |modified, added, removed| # ... } listener.start listener.ignore! /\.pkg/ # overwrite all patterns and only ignore pkg extension. listener.ignore /\.rb/ # ignore rb extension in addition of pkg. sleep ``` -------------------------------- ### CLI Usage - Basic Watch Source: https://context7.com/guard/listen/llms.txt Basic usage of the Listen CLI to watch the current directory for file changes. ```bash $ listen ``` -------------------------------- ### CLI Usage - Watch Specific Directories Source: https://context7.com/guard/listen/llms.txt Use the Listen CLI to watch one or more specific directories for file changes. ```bash $ listen -d /path/to/app /path/to/config ``` -------------------------------- ### Listen.adapter_warn_behavior - Configure Adapter Warnings Source: https://context7.com/guard/listen/llms.txt Control how Listen reports adapter-related warnings (like polling fallback messages). ```APIDOC ## Listen.adapter_warn_behavior - Configure Adapter Warnings ### Description Control how Listen reports adapter-related warnings (like polling fallback messages). ### Method `Listen.adapter_warn_behavior = behavior` ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' # Option 1: Default - use Kernel#warn (writes to STDERR) Listen.adapter_warn_behavior = :warn # Option 2: Log to Listen.logger Listen.adapter_warn_behavior = :log # Option 3: Suppress all warnings Listen.adapter_warn_behavior = :silent # Option 4: Custom callback for conditional handling Listen.adapter_warn_behavior = ->(message) do case message when /Listen will be polling for changes/ :silent # Suppress polling warning (expected in VM) when /directory is already being watched/ :log # Log to logger else :warn # Default warning behavior end end listener = Listen.to('/srv/app') do |modified, added, removed| puts modified end listener.start sleep ``` ### Response None (configures global warning behavior) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listener Options - Configure Listener Behavior Source: https://context7.com/guard/listen/llms.txt Pass options hash after directory paths to customize listener behavior including latency, relative paths, polling mode, and wait delay between callbacks. ```APIDOC ## Listener Options - Configure Listener Behavior ### Description Customizes the behavior of the file system listener using a hash of options. ### Method Listen.to(directories, options, &callback) ### Parameters #### Path Parameters - **directories** (string | Array) - Required - One or more directory paths to watch. - **options** (Hash) - Optional - Configuration options for the listener. - **ignore** (Regexp | Array) - Patterns to ignore (evaluated against relative paths). - **ignore!** (Regexp | Array) - Override default ignores entirely. - **only** (Regexp | Array) - Only watch specific file patterns (evaluated against relative file paths). - **latency** (Float) - Delay between checking for changes in seconds. Default: 0.25 (1.0 for polling). - **wait_for_delay** (Float) - Delay between callback invocations when changes exist. Default: 0.10. - **force_polling** (Boolean) - Force the use of the polling adapter. Default: false. - **relative** (Boolean) - Return relative paths instead of absolute. Default: false. - **polling_fallback_message** (String | false) - Custom message for polling mode or false to disable. Default: nil. - **callback** (Proc) - Required - A block that receives three arrays: modified, added, and removed file paths. ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app', ignore: [%r{/tmp/}, /\.pid$/, /\.log$/], only: /\.(rb|erb|haml)$/, latency: 0.5, wait_for_delay: 4, force_polling: true, relative: true ) do |modified, added, removed| puts "Changes detected!" end listener.start sleep ``` ### Response #### Success Response (200) Returns a Listener object. #### Response Example ```ruby # Listener object instance ``` ``` -------------------------------- ### Configure Listen Adapter Warning Behavior Source: https://github.com/guard/listen/blob/master/README.md Set the behavior for adapter warnings using symbols like :warn, :log, or :silent. Defaults to :warn. ```ruby Listen.adapter_warn_behavior = :warn Listen.adapter_warn_behavior = :log Listen.adapter_warn_behavior = :silent ``` -------------------------------- ### Listen.adapter_warn_behavior - Configure Adapter Warnings Source: https://context7.com/guard/listen/llms.txt Control how Listen reports adapter-related warnings, such as polling fallback messages. Options include default warning, logging to Listen.logger, suppressing warnings, or a custom callback. ```ruby require 'listen' # Option 1: Default - use Kernel#warn (writes to STDERR) Listen.adapter_warn_behavior = :warn # Option 2: Log to Listen.logger Listen.adapter_warn_behavior = :log # Option 3: Suppress all warnings Listen.adapter_warn_behavior = :silent # Option 4: Custom callback for conditional handling Listen.adapter_warn_behavior = ->(message) do case message when /Listen will be polling for changes/ :silent # Suppress polling warning (expected in VM) when /directory is already being watched/ :log # Log to logger else :warn # Default warning behavior end end listener = Listen.to('/srv/app') do |modified, added, removed| puts modified end listener.start sleep ``` -------------------------------- ### Add rb-kqueue Adapter Gem to Gemfile Source: https://github.com/guard/listen/blob/master/README.md For *BSD users, add the 'rb-kqueue' gem to your Gemfile for adapter support instead of polling. ```ruby gem 'rb-kqueue', '>= 0.2' ``` -------------------------------- ### CLI Usage - Relative Paths Source: https://context7.com/guard/listen/llms.txt Use the Listen CLI with the relative flag to process paths relative to the current directory. ```bash $ listen -r -d /srv/app ``` -------------------------------- ### Set Debugging Level via Environment Variable Source: https://github.com/guard/listen/blob/master/README.md Shows how to set the logging level for the Listen gem using the `LISTEN_GEM_DEBUGGING` environment variable. Supported levels include debug, info, warn, error, and fatal. ```bash export LISTEN_GEM_DEBUGGING=debug # or 2 [deprecated] export LISTEN_GEM_DEBUGGING=info # or 1 or true or yes [deprecated] export LISTEN_GEM_DEBUGGING=warn export LISTEN_GEM_DEBUGGING=fatal export LISTEN_GEM_DEBUGGING=error ``` -------------------------------- ### CLI Usage - Verbose Output Source: https://context7.com/guard/listen/llms.txt Enable verbose mode with the Listen CLI to see all file changes. ```bash $ listen -v -d /srv/app ``` -------------------------------- ### Set Custom Logger Source: https://github.com/guard/listen/blob/master/README.md Illustrates how to set a custom logger for the Listen gem, such as using `Rails.logger`. ```ruby Listen.logger = Rails.logger ``` -------------------------------- ### Custom Listen Adapter Warning Behavior with Lambda Source: https://github.com/guard/listen/blob/master/README.md Define custom logic for adapter warnings using a lambda or proc that inspects the warning message. This allows conditional silencing or logging. ```ruby Listen.adapter_warn_behavior = ->(message) do case message when /Listen will be polling for changes/ :silent when /directory is already being watched/ :log else :warn end end ``` -------------------------------- ### Listener#ignore! - Replace All Ignore Patterns Source: https://context7.com/guard/listen/llms.txt Completely replaces all existing ignore patterns (including defaults) with the specified patterns. ```APIDOC ## Listener#ignore! - Replace All Ignore Patterns ### Description Completely replaces all existing ignore patterns (including defaults) with the specified patterns. ### Method `listener.ignore!(pattern)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app', ignore: [/.git/, /node_modules/] ) do |modified, added, removed| puts "Changes detected" end listener.start # Replace ALL ignore patterns - removes defaults too! listener.ignore!(/\.pkg$/) # Now ONLY .pkg files are ignored # Add back additional patterns as needed listener.ignore(/\.tmp$/) sleep ``` ### Response None (modifies listener behavior) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Check Current inotify Watch Limit Source: https://github.com/guard/listen/blob/master/README.md Execute this command to view the current system limit for user inotify watches. This is useful for diagnosing issues where the limit is too low. ```bash $ cat /proc/sys/fs/inotify/max_user_watches ``` -------------------------------- ### Listen.logger - Configure Logging Source: https://context7.com/guard/listen/llms.txt Configure Listen's logger for debugging and monitoring. Set via environment variable or programmatically. ```APIDOC ## Listen.logger - Configure Logging ### Description Configure Listen's logger for debugging and monitoring. Set via environment variable or programmatically. ### Method `Listen.logger = logger_instance` ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' require 'logger' # Option 1: Use Rails logger Listen.logger = Rails.logger # Option 2: Custom logger Listen.logger = Logger.new(STDOUT) Listen.logger.level = Logger::DEBUG # Option 3: Disable logging entirely Listen.logger = Logger.new('/dev/null') # Option 4: Environment variable (set before requiring listen) # export LISTEN_GEM_DEBUGGING=debug # debug, info, warn, error, fatal listener = Listen.to('/srv/app') do |modified, added, removed| # Changes will be logged at configured level end listener.start sleep ``` ### Response None (configures global logger) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listener#ignore! - Replace All Ignore Patterns Source: https://context7.com/guard/listen/llms.txt Completely replaces all existing ignore patterns (including defaults) with the specified patterns. Use this when you need to reset ignore rules. ```ruby require 'listen' listener = Listen.to('/srv/app', ignore: [/\.git/, /node_modules/] ) do |modified, added, removed| puts "Changes detected" end listener.start # Replace ALL ignore patterns - removes defaults too! listener.ignore!(/\.pkg$/) # Now ONLY .pkg files are ignored # Add back additional patterns as needed listener.ignore(/\.tmp$/) sleep ``` -------------------------------- ### Listener#ignore - Add Ignore Patterns Source: https://context7.com/guard/listen/llms.txt Dynamically add patterns to ignore after the listener is created. Patterns are evaluated against relative file paths. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Changes: #{modified + added}" end listener.start # Add ignore patterns dynamically listener.ignore(/\.tmp$/) # Ignore .tmp files listener.ignore(%r{/cache/}) # Ignore cache directory listener.ignore(/backup_\d+\.sql/) # Ignore backup SQL files # Multiple patterns at once listener.ignore([/\.swp$/, /~$/]) sleep ``` -------------------------------- ### Listener#ignore - Add Ignore Patterns Source: https://context7.com/guard/listen/llms.txt Dynamically add patterns to ignore after the listener is created. Patterns are evaluated against relative file paths. ```APIDOC ## Listener#ignore - Add Ignore Patterns ### Description Dynamically add patterns to ignore after the listener is created. Patterns are evaluated against relative file paths. ### Method `listener.ignore(pattern)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Changes: #{modified + added}" end listener.start # Add ignore patterns dynamically listener.ignore(/\.tmp$/) # Ignore .tmp files listener.ignore(%r{/cache/}) # Ignore cache directory listener.ignore(/backup_\d+\.sql/) # Ignore backup SQL files # Multiple patterns at once listener.ignore([/\.swp$/, /~$/]) sleep ``` ### Response None (modifies listener behavior) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listen Gem Raw and Final Changes Output Source: https://github.com/guard/listen/blob/master/README.md These log messages show the raw file system events detected by Listen and the processed, relevant changes. This is crucial for understanding how Listen interprets file modifications. ```log INFO -- : listen: raw changes: [[:added, "/home/me/foo"]] INFO -- : listen: final changes: {:modified=>[], :added=>["/home/me/foo"], :removed=>[]} ``` -------------------------------- ### Increase Linux inotify Max User Watches (ArchLinux) Source: https://github.com/guard/listen/blob/master/README.md Command to update the inotify max user watches setting on ArchLinux by modifying a configuration file in /etc/sysctl.d/. ```bash sudo sh -c "echo fs.inotify.max_user_watches=524288 > /etc/sysctl.d/40-max-user-watches.conf" sudo sysctl --system ``` -------------------------------- ### Increase Linux inotify Max User Watches (Debian/RedHat) Source: https://github.com/guard/listen/blob/master/README.md Command to increase the maximum number of inotify watches for the system on Debian/RedHat based Linux distributions. ```bash sudo sh -c "echo fs.inotify.max_user_watches=524288 >> /etc/sysctl.conf" sudo sysctl -p ``` -------------------------------- ### Listen.stop - Stop All Listeners Source: https://context7.com/guard/listen/llms.txt Class method to stop all active listeners at once. Useful for cleanup on process shutdown. ```APIDOC ## Listen.stop - Stop All Listeners ### Description Class method to stop all active listeners at once. Useful for cleanup on process shutdown. ### Method `Listen.stop` ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' # Create multiple listeners listener1 = Listen.to('/srv/app') { |m, a, r| puts "App: #{m}" } listener2 = Listen.to('/srv/config') { |m, a, r| puts "Config: #{m}" } listener3 = Listen.to('/srv/lib') { |m, a, r| puts "Lib: #{m}" } listener1.start listener2.start listener3.start # Graceful shutdown of ALL listeners at_exit do Listen.stop # Stops listener1, listener2, and listener3 end Signal.trap('INT') do Listen.stop exit end sleep ``` ### Response None (stops all listeners) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listen.stop - Stop All Listeners Source: https://context7.com/guard/listen/llms.txt Class method to stop all active listeners at once. Useful for cleanup on process shutdown. ```ruby require 'listen' # Create multiple listeners listener1 = Listen.to('/srv/app') { |m, a, r| puts "App: #{m}" } listener2 = Listen.to('/srv/config') { |m, a, r| puts "Config: #{m}" } listener3 = Listen.to('/srv/lib') { |m, a, r| puts "Lib: #{m}" } listener1.start listener2.start listener3.start # Graceful shutdown of ALL listeners at_exit do Listen.stop # Stops listener1, listener2, and listener3 end Signal.trap('INT') do Listen.stop exit end sleep ``` -------------------------------- ### Listen.logger - Configure Logging Source: https://context7.com/guard/listen/llms.txt Configure Listen's logger for debugging and monitoring. Set via environment variable or programmatically. Options include using Rails logger, a custom logger, or disabling logging. ```ruby require 'listen' require 'logger' # Option 1: Use Rails logger Listen.logger = Rails.logger # Option 2: Custom logger Listen.logger = Logger.new(STDOUT) Listen.logger.level = Logger::DEBUG # Option 3: Disable logging entirely Listen.logger = Logger.new('/dev/null') # Option 4: Environment variable (set before requiring listen) # export LISTEN_GEM_DEBUGGING=debug # debug, info, warn, error, fatal listener = Listen.to('/srv/app') do |modified, added, removed| # Changes will be logged at configured level end listener.start sleep ``` -------------------------------- ### Listener#only - Filter to Specific File Types Source: https://context7.com/guard/listen/llms.txt Restricts the listener to only report changes for files matching the specified patterns. Patterns are evaluated against relative file paths only. ```ruby require 'listen' # Watch only Ruby files listener = Listen.to('/srv/app', only: /\.rb$/) do |modified, added, removed| modified.each { |f| puts "Ruby file changed: #{f}" } end listener.start # Dynamically change the only filter listener.only(/_spec\.rb$/) # Now only watch spec files # Watch multiple file types listener.only(/\.(rb|rake|gemspec)$/) sleep ``` -------------------------------- ### Pause Event Processing with Listener#pause Source: https://context7.com/guard/listen/llms.txt Temporarily pauses the listener from invoking callbacks while still collecting changes. Resume processing with `listener.start`. This is useful during intensive operations. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Processing: #{modified + added + removed}" end listener.start # Pause during a long operation listener.pause puts listener.paused? # => true puts listener.processing? # => false # Perform some operation without triggering callbacks system('bundle install') # Resume processing - any accumulated changes will be processed listener.start puts listener.processing? # => true sleep ``` -------------------------------- ### Permanently Increase inotify Watch Limit Source: https://github.com/guard/listen/blob/master/README.md Modify the system's configuration to permanently increase the maximum number of user inotify watches. This change persists across reboots. ```bash $ sudo sh -c "echo fs.inotify.max_user_watches=524288 >> /etc/sysctl.conf" $ sudo sysctl -p ``` -------------------------------- ### Stop Monitoring with Listener#stop Source: https://context7.com/guard/listen/llms.txt Completely stops the listener, clearing any accumulated changes. Use Signal traps for graceful shutdown. ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| modified.each { |f| puts "Modified: #{f}" } end listener.start # Handle graceful shutdown Signal.trap('INT') do puts 'Shutting down...' listener.stop exit end Signal.trap('TERM') do listener.stop exit end sleep ``` -------------------------------- ### Temporarily Increase inotify Watch Limit Source: https://github.com/guard/listen/blob/master/README.md Use this command to temporarily increase the maximum number of user inotify watches for the current session. This is a quick way to test if a higher limit resolves issues. ```bash $ sudo sysctl fs.inotify.max_user_watches=524288 $ sudo sysctl -p ``` -------------------------------- ### Listener#only - Filter to Specific File Types Source: https://context7.com/guard/listen/llms.txt Restricts the listener to only report changes for files matching the specified patterns. Patterns are evaluated against relative file paths only (not directories). ```APIDOC ## Listener#only - Filter to Specific File Types ### Description Restricts the listener to only report changes for files matching the specified patterns. Patterns are evaluated against relative file paths only (not directories). ### Method `listener.only(pattern)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require 'listen' # Watch only Ruby files listener = Listen.to('/srv/app', only: /\.rb$/) do |modified, added, removed| modified.each { |f| puts "Ruby file changed: #{f}" } end listener.start # Dynamically change the only filter listener.only(/_spec\.rb$/) # Now only watch spec files # Watch multiple file types listener.only(/\.(rb|rake|gemspec)$/) sleep ``` ### Response None (modifies listener behavior) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Listener#stop - Stop Monitoring Source: https://context7.com/guard/listen/llms.txt Completely stops both listening for events and processing them. Unlike pause, this clears any accumulated changes. ```APIDOC ## Listener#stop - Stop Monitoring ### Description Completely stops both listening for events and processing them. Clears any accumulated changes. ### Method listener.stop ### Parameters None ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| modified.each { |f| puts "Modified: #{f}" } end listener.start Signal.trap('INT') do puts 'Shutting down...' listener.stop exit end Signal.trap('TERM') do listener.stop exit end sleep ``` ### Response #### Success Response (200) Stops the listener and clears accumulated changes. #### Response Example ```ruby # Listener stopped ``` ``` -------------------------------- ### Disable Listen Logging Source: https://github.com/guard/listen/blob/master/README.md Provides a method to disable all logging for the Listen gem by redirecting output to `/dev/null`. ```ruby Listen.logger = ::Logger.new('/dev/null') ``` -------------------------------- ### Listener#pause - Pause Event Processing Source: https://context7.com/guard/listen/llms.txt Pauses the listener from invoking callbacks while continuing to collect changes in the background. Useful for temporarily suspending notifications during intensive operations. ```APIDOC ## Listener#pause - Pause Event Processing ### Description Pauses the listener from invoking callbacks while continuing to collect changes in the background. ### Method listener.pause ### Parameters None ### Request Example ```ruby require 'listen' listener = Listen.to('/srv/app') do |modified, added, removed| puts "Processing: #{modified + added + removed}" end listener.start listener.pause puts listener.paused? # => true puts listener.processing? # => false system('bundle install') listener.start puts listener.processing? # => true sleep ``` ### Response #### Success Response (200) Pauses the listener's event processing. #### Response Example ```ruby # Listener paused ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.