Class: Logg::Dispatcher::Render

Inherits:
Object
  • Object
show all
Defined in:
lib/logg/core.rb

Instance Method Summary collapse

Instance Method Details

#detect_path(path) ⇒ Object



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

def detect_path(path)
  if path.respond_to?(:path)
    path.path
  elsif path.respond_to?(:realpath)
    path.to_s
  elsif path.respond_to?(:to_s)
    path.to_s
  else
    raise ArgumentError, 'Missing file or a filepath.'
  end
end

#detect_syntax(options) ⇒ Object



72
73
74
75
76
77
# File 'lib/logg/core.rb', line 72

def detect_syntax(options)
  unless options.has_key?(:as)
    raise ArgumentError, 'Missing template syntax specified as the :as option.'
  end
  options[:as].to_s
end

#fetch_template(args, path) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/logg/core.rb', line 56

def fetch_template(args, path)
  if args[:as]
    begin
      test_path = Pathname.new(path)
      raise ArgumentError, "Invalid filepath #{path}" unless test_path.file?
    rescue
      test_path = Pathname.new(path + ".#{args[:as].to_s.downcase}")
      raise ArgumentError, "Invalid filepath #{path}" unless test_path.file?
      path = test_path.to_s
    end
    Tilt.const_get("#{args[:as].to_s.downcase.capitalize}Template").new(path)
  else
    Tilt.new(path)
  end
end

#render(path, *args) ⇒ String

Render a template. Just a mere proxy for Tilt::Template#render method, the first argument being the filepath or file, and the latter, the usual arguments for Tilt’s #render.

Parameters:

  • path (String, #path, #realpath)

    filepath or an object behaving like a legacy File

  • obj (Object)

    context object the template will be rendered within

  • args (Hash)

    rendering context

  • [Symbol] (Hash)

    a customizable set of options

  • [Object] (Hash)

    a customizable set of options

  • [Hash] (Hash)

    a customizable set of options

Returns:

  • (String)

    the interpolated template



24
25
26
27
28
29
# File 'lib/logg/core.rb', line 24

def render(path, *args)
  args = args.first
  path = detect_path(path)
  tpl  = fetch_template(args, path)
  tpl.render(args[:data], args[:locals])
end

#render_inline(content, *args) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/logg/core.rb', line 31

def render_inline(content, *args)
  args   = args.first
  syntax = detect_syntax(args)
  res    = Object

  Better::Tempfile.open(['dummylogg', ".#{syntax}"]) do |f|
    f.write(content)
    f.rewind
    res = Tilt.new(f.path).render(args[:data], args[:locals])
  end
  res
end