Class: Alephant::Renderer

Inherits:
Object
  • Object
show all
Defined in:
lib/alephant/models/renderer.rb

Constant Summary collapse

DEFAULT_LOCATION =
'views'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, view_base_path = nil) ⇒ Renderer

Returns a new instance of Renderer.



10
11
12
13
14
15
16
17
# File 'lib/alephant/models/renderer.rb', line 10

def initialize(id, view_base_path=nil)
  @logger = ::Alephant.logger

  @id = id
  self.base_path = view_base_path unless view_base_path.nil?

  @logger.info("Renderer.initialize: end with self.base_path set to #{self.base_path}")
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



8
9
10
# File 'lib/alephant/models/renderer.rb', line 8

def id
  @id
end

Instance Method Details

#base_pathObject



27
28
29
# File 'lib/alephant/models/renderer.rb', line 27

def base_path
  @base_path || DEFAULT_LOCATION
end

#base_path=(path) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/alephant/models/renderer.rb', line 31

def base_path=(path)
  if File.directory?(path)
    @base_path = path
  else
    @logger.error("Renderer.base_path=(path): error of invalid view path #{path}")
    raise Errors::InvalidViewPath
  end
end

#model(id, data) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/alephant/models/renderer.rb', line 40

def model(id, data)
  model_location = File.join(base_path, 'models', "#{id}.rb")

  begin
    require model_location
    klass = ::Alephant::Views.get_registered_class(id)
    @logger.info("Renderer.model: klass set to #{klass}")
  rescue Exception => e
    @logger.error("Renderer.model: view model with id #{id} not found")
    raise Errors::ViewModelNotFound
  end

  @logger.info("Renderer.model: creating new klass with data #{data}")
  klass.new(data)
end

#render(data) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/alephant/models/renderer.rb', line 19

def render(data)
  @logger.info("Renderer.render: rendered template with id #{id}")
  Mustache.render(
    template(@id),
    model(@id,data)
  )
end

#template(id) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/alephant/models/renderer.rb', line 56

def template(id)
  template_location = File.join(base_path,'templates',"#{id}.mustache")
  begin
    @logger.info("Renderer.template: #{template_location}")
    File.open(template_location).read
  rescue Exception => e
    @logger.error("Renderer.template: view tempalte with id #{id} not found")
    raise Errors::ViewTemplateNotFound
  end
end