Class: Dry::View::Context Abstract

Inherits:
Object
  • Object
show all
Includes:
DecoratedAttributes
Defined in:
lib/dry/view/context.rb

Overview

This class is abstract.

Subclass this and add your own methods (along with a custom ‘#initialize` if you wish to inject dependencies)

Provides a baseline environment across all the templates, parts and scopes in a given rendering.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DecoratedAttributes

included

Constructor Details

#initialize(render_env: nil, **options) ⇒ Context

Returns a new instance of Context

In subclasses, you should include an ‘**options` parameter and pass _all arguments_ to `super`. This allows Context to make copies of itself while preserving your dependencies.

Examples:

class MyContext < Dry::View::Context
  # Injected dependency
  attr_reader :assets

  def initialize(assets:, **options)
    @assets = assets
    super
  end
end


39
40
41
42
# File 'lib/dry/view/context.rb', line 39

def initialize(render_env: nil, **options)
  @_render_env = render_env
  @_options = options
end

Instance Attribute Details

#_optionsObject (readonly)



19
20
21
# File 'lib/dry/view/context.rb', line 19

def _options
  @_options
end

#_render_envObject (readonly)



19
20
21
# File 'lib/dry/view/context.rb', line 19

def _render_env
  @_render_env
end

Instance Method Details

#for_render_env(render_env) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



45
46
47
48
49
# File 'lib/dry/view/context.rb', line 45

def for_render_env(render_env)
  return self if render_env == _render_env

  self.class.new(**_options.merge(render_env: render_env))
end

#with(**new_options) ⇒ Object

Returns a copy of the Context with new options merged in.

This may be useful to supply values for dependencies that are optional when initializing your custom Context subclass.

Examples:

class MyContext < Dry::View::Context
  # Injected dependencies (request is optional)
  attr_reader :assets, :request

  def initialize(assets:, request: nil, **options)
    @assets = assets
    @request = reuqest
    super
  end
end

my_context = MyContext.new(assets: assets)
my_context_with_request = my_context.with(request: request)


72
73
74
75
76
77
# File 'lib/dry/view/context.rb', line 72

def with(**new_options)
  self.class.new(
    render_env: _render_env,
    **_options.merge(new_options)
  )
end