### Check if a provider has been started Source: https://context7.com/dry-rb/dry-rails/llms.txt Use `started?` to check if a specific provider within the container has been initialized. ```ruby Dummy::Container.started?(:persistence) # => true / false ``` -------------------------------- ### Define and Manage Bootable Providers Source: https://context7.com/dry-rb/dry-rails/llms.txt Custom providers with lifecycle hooks are placed in `config/system/boot/`. They are lazily loaded on first resolution or can be started explicitly. Use `register_provider` to define them. ```ruby # config/system/boot/persistence.rb Dummy::Container.register_provider(:persistence) do prepare do require "sequel" end start do db = Sequel.connect(ENV["DATABASE_URL"]) target.register("persistence.db", db) end stop do target["persistence.db"].disconnect end end # Explicit start (e.g., in a rake task or spec setup) Dummy::Container.start(:persistence) # Lazy access — provider starts automatically on first use user_repo = UserRepo.new user_repo.db # => Sequel::Database instance (provider started implicitly) ``` -------------------------------- ### Restoring Default Features in Dry::Rails Container Source: https://context7.com/dry-rb/dry-rails/llms.txt Illustrates how to restore the container's features to their default state using the pristine configuration. This is useful for resetting the container to its initial setup. ```ruby Dry::Rails.container do config.features = config.pristine.features end ``` -------------------------------- ### Resetting Features in Dry::Rails Container Source: https://context7.com/dry-rb/dry-rails/llms.txt Shows how to reset the features within the Dry::Rails container, typically used for dynamic configuration or in test setups. This clears all currently configured features. ```ruby Dry::Rails.container do config.features = [] end ``` -------------------------------- ### Injecting Dependencies with MyApp::Import Source: https://context7.com/dry-rb/dry-rails/llms.txt Demonstrates how to include dependencies like mailer and logger into a service class using MyApp::Import. Ensure these dependencies are registered in the container. ```ruby class ReportService include MyApp::Import[:mailer, :logger] def generate logger.info("Generating report") mailer.deliver(report_pdf) end end ``` -------------------------------- ### Auto-Register Components and Resolve from Container Source: https://context7.com/dry-rb/dry-rails/llms.txt Components placed in registered directories are automatically resolved by key. The key for files under `app/` subdirectories strips the first path segment. Use the container constant to access registered components. ```ruby # app/operations/create_user.rb class CreateUser def call(params) # business logic end end # app/services/github.rb class Github def initialize(token:) @token = token end end # Resolved from anywhere using the container constant set in the app namespace # (e.g., MyApp::Container or Dummy::Container) container = Dummy::Container container["create_user"] # => # container["github"] # => # container[:mailer] # => # (Symbol or String keys both work) ``` -------------------------------- ### Manual Container Finalization Source: https://context7.com/dry-rb/dry-rails/llms.txt Demonstrates how to manually finalize the container. This process is usually handled automatically by the Railtie during the Rails boot process. ```ruby Dry::Rails::Railtie.finalize! ``` -------------------------------- ### Configure Container Initialization Source: https://context7.com/dry-rb/dry-rails/llms.txt Configure the application container within a Rails initializer. This block allows customization of component directories, namespaces, memoization, and features before the application boots. ```ruby require "dry/rails" Dry::Rails.container do # Register "lib/my_app/**/*.rb" components, stripping the "my_app" namespace from keys config.component_dirs.add "lib" do |dir| dir.namespaces.add "my_app", key: nil end # Register "app/operations/**/*.rb" — keys are derived from filenames, e.g. "create_user" config.component_dirs.add "app/operations" # Register "app/services/**/*.rb" config.component_dirs.add "app/services" # Register "app/workers/**/*.rb" and memoize instances (singleton per container) config.component_dirs.add("app/workers") do |dir| dir.memoize = true end # Disable specific features (default: all three enabled) # config.features = %i[controller_helpers safe_params] # Rename the auto-injector constant (default: "Deps") # config.auto_inject_constant = "Import" # Rename the container constant (default: "Container") # config.container_constant = "Container" end ``` -------------------------------- ### Dependency Injection with Deps Auto-Injector Source: https://context7.com/dry-rb/dry-rails/llms.txt The `Deps` constant provides constructor-level dependency injection via `include Deps[...]`. Dependencies are injected as keyword arguments and stored as accessible readers. Use fully-qualified namespaces for specific containers. ```ruby # lib/my_app/notifier.rb module MyApp class Notifier include Deps[:mailer] # injects "mailer" as #mailer reader # include Deps["mailer"] # equivalent string key form def notify(user) mailer.deliver(user) end end end # app/workers/mailer_worker.rb class MailerWorker include Dummy::Deps["mailer"] # fully-qualified namespace form def perform(payload) mailer.send_email(payload) end end # app/models/user_repo.rb — injecting a bootable provider component class UserRepo include Dummy::Deps["persistence.db"] # dot-separated nested key def find(id) db.query("SELECT * FROM users WHERE id = ?", id) end end ``` -------------------------------- ### Accessing the Finalized Container Source: https://context7.com/dry-rb/dry-rails/llms.txt Shows how to access the container instance after it has been finalized. The Railtie exposes the finalized container for use throughout the application. ```ruby Dry::Rails::Railtie.container # => MyApp::Container (after finalize!) ``` -------------------------------- ### Resolve a component directly by key in Rails controllers Source: https://context7.com/dry-rb/dry-rails/llms.txt When `controller_helpers` is enabled, use the `#resolve` instance method within controller actions to access container components by their keys. ```ruby class OrdersController < ApplicationController def index # Resolve a component directly by key within an action orders_query = resolve("orders.query") render json: orders_query.call(current_user) end def create # Access the full container result = container["create_order"].(order_params) if result.success? render json: result.value!, status: :created else render json: {errors: result.failure}, status: :unprocessable_entity end end end ``` -------------------------------- ### Configure Dry-Rails container features and constants Source: https://context7.com/dry-rb/dry-rails/llms.txt Customize which Dry-Rails features are enabled and modify the names of the auto-injector and container constants via the `Dry::Rails.container` block in `config/initializers/system.rb`. ```ruby # config/initializers/system.rb Dry::Rails.container do # Enable only specific features config.features = %i[application_contract safe_params] # config.features = [] # disable all features # Change the auto-injector constant name (default: "Deps") config.auto_inject_constant = "Import" # Change the container constant name (default: "Container") config.container_constant = "System" end # After boot, constants are defined in the app namespace: # MyApp::System => the container ``` -------------------------------- ### Define a preconfigured validation contract in Rails Source: https://context7.com/dry-rb/dry-rails/llms.txt The `application_contract` feature provides an `ApplicationContract` base class, preconfigured for I18n and loading locale files from `config/locales/`. Use it to define reusable validation schemas. ```ruby # app/contracts/user_contract.rb (or lib/my_app/user_contract.rb) class UserContract < ApplicationContract params do required(:name).filled(:string) required(:email).filled(:string) optional(:age).maybe(:integer) end rule(:email) do key.failure("must be a valid email") unless values[:email].include?("@") end end # Usage in a controller or service contract = UserContract.new result = contract.(name: "", email: "not-an-email") result.success? # => false result.errors.to_h # => { name: ["must be filled"], email: ["must be a valid email"] } # I18n-backed messages from config/locales/en.yml I18n.with_locale(:en) do UserContract.new.(name: "").errors[:name] # => ["cannot be blank"] (from contracts: namespace in locale file) end I18n.with_locale(:pl) do UserContract.new.(name: "").errors[:name] # => ["nie może być puste"] end # Resolved directly from the container Dummy::Container[:user_contract] # => # ``` -------------------------------- ### Checking Container Frozen State in Test Environment Source: https://context7.com/dry-rb/dry-rails/llms.txt Verifies if the container is frozen. In the test environment (Rails.env.test?), the container is typically not frozen, allowing for mutations and reloads. ```ruby Dummy::Container.frozen? # => false (Rails.env.test?) ``` -------------------------------- ### Define schema-validated request parameters in Rails controllers Source: https://context7.com/dry-rb/dry-rails/llms.txt Use the `.schema` class macro to define `Dry::Schema::Params` for controller actions. The validated parameters are exposed via the `#safe_params` instance method. ```ruby class UsersController < ApplicationController # Schema applied to the :show action — coerces and validates "id" schema(:show) do required(:id).value(:integer) end # Same schema applied to multiple actions at once schema(:new, :create) do required(:name).filled(:string) optional(:email).maybe(:string) end def show if safe_params.success? render json: {id: safe_params[:id], name: "Jane"} else # safe_params.errors.to_h => { id: ["must be an integer"] } render json: {errors: safe_params.errors.to_h}, status: :unprocessable_entity end end def create if safe_params.success? user = CreateUser.new.(safe_params.to_h) render json: user, status: :created else render json: {errors: safe_params.errors.to_h}, status: :unprocessable_entity end end end # Works identically with ActionController::API class ApiUsersController < ActionController::API schema(:show) do required(:id).value(:integer) end def show if safe_params.success? render json: {id: safe_params[:id]} else render json: {errors: safe_params.errors.to_h}, status: :unprocessable_entity end end end # Using safe_params inside a before_action callback class SafeParamsCallbacksController < ApplicationController before_action do if safe_params&.failure? head 422 else head 200 end end schema(:show) do required(:id).value(:integer) end def show; end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.