Module: Keynote::Inline

Defined in:
lib/keynote/inline.rb

Overview

The ‘Inline` mixin lets you write inline templates as comments inside the body of a presenter method. You can use any template language supported by Rails.

## Basic usage

After extending the ‘Keynote::Inline` module in your presenter class, you can generate HTML by calling the `erb` method and passing a template as a string to it:

def link
  erb do
    <<~ERB
      <%= link_to user_url(current_user) do %>
        <%= image_tag("image1.jpg") %>
         <%= image_tag("image2.jpg") %>
      <% end %>
    ERB
  end
end

Calling this method renders the ERB template, including passing the calls to ‘link_to`, `user_url`, `current_user`, and `image_tag` back to the presenter object (and then to the view).

## Passing variables

You can pass locals as keyword arguments to the ‘erb` method:

def with_locals
  x = 1
  y = 2

  erb(x:, y:) do
    %q(<%= x + y %>)
  end
end

## The ‘inline` method

If you want to use template languages other than ERB, you have to define methods for them by calling the #inline method on a presenter class:

class MyPresenter < Keynote::Presenter
  extend Keynote::Inline
  presents :user, :account
  inline :haml
end

This defines a ‘#haml` instance method on the `MyPresenter` class.

If you want to make inline templates available to all of your presenters, you can add an initializer like this to your application:

class Keynote::Presenter
  extend Keynote::Inline
  inline :haml, :slim
end

This will add ‘#erb`, `#haml`, and `#slim` instance methods to all of your presenters.

Defined Under Namespace

Modules: InstanceMethods Classes: Cache, Renderer, Template

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

Extending ‘Keynote::Inline` automatically creates an `erb` method on the base class.



102
103
104
105
# File 'lib/keynote/inline.rb', line 102

def self.extended(base)
  base.inline :erb
  base.include InstanceMethods
end

Instance Method Details

#inline(*formats) ⇒ Object

For each template format given as a parameter, add an instance method that can be called to render an inline template in that format. Any file extension supported by Rails is a valid parameter.

Examples:

class UserPresenter < Keynote::Presenter
  presents :user
  inline :haml

  def header
    full_name = "#{user.first_name} #{user.last_name}"

    haml(full_name:) do
      <<~HAML
        div#header
          h1= full_name
          h3= user.most_recent_status
      HAML
    end
  end
end


89
90
91
92
93
94
95
96
97
98
# File 'lib/keynote/inline.rb', line 89

def inline(*formats)
  require "action_view/context"

  Array(formats).each do |format|
    define_method format do |**locals, &block|
      raise ArgumentError, "You must pass a block to the ##{format} method" unless block
      Renderer.new(self, locals, caller_locations(1, 1).first, block.call, format).render
    end
  end
end