Class: Shaven::Presenter

Inherits:
Object show all
Includes:
Helpers::HTML
Defined in:
lib/shaven/presenter.rb

Overview

Presenters are placeholder for all logic which is going to fill in your html templates. Remember that presenters shouldn’t contain any raw HTML code, you can generate it using html helpers (see Shaven::Helpers::HTML for details).

Simple example

class DummyPreseneter < Shaven::Presenter
  def title
    "Hello world!"
  end
end

presenter = DummyPreseneter.feed("<!DOCTYPE html><html><body><h1 rb="title">Example...</h1></body><html>")
presenter.to_html # => ...

DOM Manipulation

If your presenter method has one argument, then related DOM node will be passed to it while transformation process. You can use it to change its attributes or content, replace it with other node or text, remove it, etc.

class DummyPresenter < Shaven::Presenter
  def title(node)
    node.update!(:id => "title") { "Hello world!" }
  end
end

HTML helpers

Shaven’s presenters provides set of helpers to generate extra html nodes. Take a look at example:

class DummyPresenter < Shaven::Presenter
  def 
    a(:href => ) { "Login to your account!" }
  end

  def title
    tag(:h1, :id => "title") { "Hello world!" }
  end
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers::HTML

#a, #div, #img, #tag

Constructor Details

#initialize(document) ⇒ Presenter

Returns a new instance of Presenter.



65
66
67
68
# File 'lib/shaven/presenter.rb', line 65

def initialize(document)
  @document = document
  @scope    = Scope.new(self)
end

Instance Attribute Details

#scopeObject (readonly)

Returns the value of attribute scope.



63
64
65
# File 'lib/shaven/presenter.rb', line 63

def scope
  @scope
end

Class Method Details

.feed(tpl) ⇒ Object



54
55
56
# File 'lib/shaven/presenter.rb', line 54

def feed(tpl)
  new(Document.new(tpl))
end

.render(tpl, context = {}) ⇒ Object



58
59
60
# File 'lib/shaven/presenter.rb', line 58

def render(tpl, context={})
  feed(tpl).render(context)
end

Instance Method Details

#compiled?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/shaven/presenter.rb', line 81

def compiled?
  !!@compiled
end

#render(context = {}) ⇒ Object Also known as: to_html



70
71
72
73
74
75
76
77
78
# File 'lib/shaven/presenter.rb', line 70

def render(context={})
  unless compiled?
    @scope.unshift(context.stringify_keys) unless context.empty?
    Transformer.apply!(@scope.with(@document.root))
    @compiled = true
  end

  @document.to_html
end