Module: Inertia::ControllerHelpers::ClassMethods

Defined in:
lib/inertia/controller_helpers.rb

Instance Method Summary collapse

Instance Method Details

#inertia_share(**options) { ... } ⇒ Object

Shares data with all Inertia responses in a controller.

This method registers a before_action that evaluates the given block in the controller instance context and merges the returned hash into the shared data. The shared data is automatically included in all Inertia responses rendered by the controller.

Multiple inertia_share calls are cumulative - each block's data is merged into the existing shared data.

Examples:

Share data for all actions

class ApplicationController < RageController::API
  inertia_share do
    { current_user: current_user&.as_json }
  end
end

Share data only for specific actions

class UsersController < ApplicationController
  inertia_share only: [:index, :show] do
    { permissions: current_user.permissions }
  end
end

Share data conditionally

class DashboardController < ApplicationController
  inertia_share if: :user_signed_in? do
    { notifications: current_user.unread_notifications }
  end
end

Parameters:

  • options (Hash)

    options passed to before_action (e.g., only:, except:, if:, unless:)

Yields:

  • Block evaluated in controller context that returns a Hash of data to share

Yield Returns:

  • (Hash)

    the data to merge into the shared props

Raises:

  • (ArgumentError)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/inertia/controller_helpers.rb', line 44

def inertia_share(**options, &block)
  raise ArgumentError, "inertia_share requires a block" unless block

  before_action(**options) do
    data = instance_eval(&block)
    return unless data

    if self.inertia_shared_data
      self.inertia_shared_data.merge!(data) #
    else
      self.inertia_shared_data = data
    end
  end
end