Class: Mousevc::View

Inherits:
Object
  • Object
show all
Defined in:
lib/mousevc/view.rb

Overview

Note:

Currently only supports ERB templates and a file naming convention of: [VIEW_NAME].txt.erb

The view rendering class of Mousevc.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ View

Create a new Mousevc::View instance



23
24
25
# File 'lib/mousevc/view.rb', line 23

def initialize(options={})
  @dir = options[:dir]
end

Instance Attribute Details

#dirString

Note:

as of v0.0.6 Mousevc requires that the views path be absolute, e.g “#{File.dirname(__FILE__)}/views”

Returns the absolute path to the views directory.

Returns:

  • (String)

    the absolute path to the views directory



18
19
20
# File 'lib/mousevc/view.rb', line 18

def dir
  @dir
end

Instance Method Details

#render(view, *args) ⇒ String

Note:

If the string passed to the view parameter is an existing file it will be used as the ERB template. Otherwise the string will be parsed as ERB.

Note:

Optionally the view output can be suppressed via setting output to false. The view will be returned as a string allowing later output e.g. render(‘view’, {:data => data}, false)

Note:

In the event that you want to suppress output and not provide any data you may substitute data for output in the parameter list e.g. render(‘view’, false)

Renders a view, passing it the given data. In the ERB template the hash variables will be available as instance variables e.g. @view_variable

Parameters:

  • view (String)

    the name of the view with .txt.erb omitted

  • args (Array)

    accepts 2 additional parameters.

    • data [Hash] the data to pass to the view (optionally omit)

    • output [Boolean] false if output is to be suppressed

Returns:

  • (String)

    the rendered view as a string



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mousevc/view.rb', line 43

def render(view, *args)
  data = args[0].is_a?(Hash) ? args[0] : {}
  output = ! (args[0] == false || args[1] == false)

  path = "#{@dir}/#{view}.txt.erb"

  view = File.file?(path) ? File.read(path) : view

  to_ivars(data)

  result = ERB.new(view).result(binding)

  puts result if output

  result
end