Sha256: 579b578df7939bfbbf0a999eb32487c66216f824e7caf3722dadf3228f0242a2

Contents?: true

Size: 1.79 KB

Versions: 9

Compression:

Stored size: 1.79 KB

Contents

require_relative "inertia_rails"

module InertiaRails
  class Renderer
    attr_reader :component, :view_data

    def initialize(component, controller, request, response, render_method, props:, view_data:)
      @component = component
      @controller = controller
      @request = request
      @response = response
      @render_method = render_method
      @props = props || {}
      @view_data = view_data || {}
    end

    def render
      if @request.headers['X-Inertia']
        @response.set_header('Vary', 'Accept')
        @response.set_header('X-Inertia', 'true')
        @render_method.call json: page, status: @response.status, content_type: Mime[:json]
      else
        @render_method.call template: 'inertia', layout: ::InertiaRails.layout, locals: (view_data).merge({page: page})
      end
    end

    private

    def props
      _props = ::InertiaRails.shared_data(@controller).merge(@props).select do |key, prop|
        if rendering_partial_component?
          key.in? partial_keys
        else
          !prop.is_a?(InertiaRails::Lazy)
        end
      end

      deep_transform_values(_props, lambda {|prop| prop.respond_to?(:call) ? @controller.instance_exec(&prop) : prop })
    end

    def page
      {
        component: component,
        props: props,
        url: @request.original_fullpath,
        version: ::InertiaRails.version,
      }
    end

    def deep_transform_values(hash, proc)
      return proc.call(hash) unless hash.is_a? Hash

      hash.transform_values {|value| deep_transform_values(value, proc)}
    end

    def partial_keys
      (@request.headers['X-Inertia-Partial-Data'] || '').split(',').compact.map(&:to_sym)
    end

    def rendering_partial_component?
      @request.inertia_partial? && @request.headers['X-Inertia-Partial-Component'] == component
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
inertia_rails-1.11.1 lib/inertia_rails/renderer.rb
inertia_rails-1.11.0 lib/inertia_rails/renderer.rb
inertia_rails-1.10.0 lib/inertia_rails/renderer.rb
inertia_rails-1.9.2 lib/inertia_rails/renderer.rb
inertia_rails-1.9.1 lib/inertia_rails/renderer.rb
inertia_rails-1.9.0 lib/inertia_rails/renderer.rb
inertia_rails-1.8.0 lib/inertia_rails/renderer.rb
inertia_rails-1.7.1 lib/inertia_rails/renderer.rb
inertia_rails-1.7.0 lib/inertia_rails/renderer.rb