Class: Rubyoshka

Inherits:
Object show all
Defined in:
lib/rubyoshka.rb,
lib/rubyoshka/html.rb,
lib/rubyoshka/version.rb,
lib/rubyoshka/compiler.rb,
lib/rubyoshka/renderer.rb

Overview

A Rubyoshka is a template representing a piece of HTML

Defined Under Namespace

Modules: Encoding, HTML Classes: Compiler, HTMLRenderer, Renderer, XMLRenderer

Constant Summary collapse

H_EMPTY =
{}.freeze
VERSION =
'0.7'
@@cache =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mode: :html, **ctx, &block) ⇒ Rubyoshka

Initializes a Rubyoshka with the given block

Parameters:

  • ctx (Hash)

    local context

  • block (Proc)

    nested HTML block

  • (void)


26
27
28
29
# File 'lib/rubyoshka.rb', line 26

def initialize(mode: :html, **ctx, &block)
  @mode = mode
  @template = ctx.empty? ? block : proc { with(**ctx, &block) }
end

Instance Attribute Details

#templateObject (readonly)

Returns the value of attribute template.



20
21
22
# File 'lib/rubyoshka.rb', line 20

def template
  @template
end

Class Method Details

.cacheObject



65
66
67
# File 'lib/rubyoshka.rb', line 65

def self.cache
  @@cache
end

.component(&block) ⇒ Object



69
70
71
# File 'lib/rubyoshka.rb', line 69

def self.component(&block)
  proc { |*args| new { instance_exec(*args, &block) } }
end

.xml(**ctx, &block) ⇒ Object



73
74
75
# File 'lib/rubyoshka.rb', line 73

def self.xml(**ctx, &block)
  new(mode: :xml, **ctx, &block)
end

Instance Method Details

#compileObject



55
56
57
# File 'lib/rubyoshka.rb', line 55

def compile
  Rubyoshka::Compiler.new.compile(self)
end

#render(context = H_EMPTY, &block) ⇒ String

Renders the associated block and returns the string result

Parameters:

  • context (Hash) (defaults to: H_EMPTY)

    context

Returns:

  • (String)


36
37
38
39
40
41
42
# File 'lib/rubyoshka.rb', line 36

def render(context = H_EMPTY, &block)
  if block
    context = context.dup if context.frozen?
    context[:__block__] = block
  end
  renderer_class.new(context, @template).to_s
end

#renderer_classObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/rubyoshka.rb', line 44

def renderer_class
  case @mode
  when :html
    HTMLRenderer
  when :xml
    XMLRenderer
  else
    raise "Invalid mode #{@mode.inspect}"
  end
end

#to_procObject



59
60
61
# File 'lib/rubyoshka.rb', line 59

def to_proc
  @template
end