Class: Rack::Component

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/component.rb,
lib/rack/component/refinements.rb,
lib/rack/component/component_cache.rb

Overview

Subclass Rack::Component to compose declarative, component-based responses to HTTP requests

Direct Known Subclasses

Memoized

Defined Under Namespace

Modules: Refinements Classes: Memoized

Constant Summary collapse

VERSION =
'0.3.0'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(*args, &block) ⇒ String, Object

Initialize a new component with the given args and render it.

Examples:

Render a HelloWorld component

class HelloWorld < Rack::Component
  def initialize(name)
    @name = name
  end

  def render
    "<h1>Hello #{@name}</h1>"
  end
end

MyComponent.call(world: 'Earth') #=> '<h1>Hello Earth</h1>'

Returns:

  • (String, Object)

    the output of instance#render



25
26
27
# File 'lib/rack/component.rb', line 25

def self.call(*args, &block)
  new(*args).render(&block)
end

Instance Method Details

#exposuresObject

Override #exposures to keep the default yield-or-return behavior of #render, but change what gets yielded or returned



41
42
43
# File 'lib/rack/component.rb', line 41

def exposures
  self
end

#renderString, Object

Override either #render or #exposures to make your component do work. By default, the behavior of #render depends on whether you call the component with a block or not: it either returns #exposures or yields to the block with #exposures as arguments.

Returns:

  • (String, Object)

    usually a string, but really whatever



35
36
37
# File 'lib/rack/component.rb', line 35

def render
  block_given? ? yield(exposures) : exposures
end