Class: Etna::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/etna/controller.rb

Constant Summary collapse

VIEW_PATH =

methods for returning a view

:VIEW_PATH

Instance Method Summary collapse

Constructor Details

#initialize(request, action = nil) ⇒ Controller

Returns a new instance of Controller.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/etna/controller.rb', line 5

def initialize(request, action = nil)
  @request = request
  @action = action
  @response = Rack::Response.new
  @params = @request.env['rack.request.params']
  @errors = []
  @server = @request.env['etna.server']
  @logger = @request.env['etna.logger']
  @user = @request.env['etna.user']
  @request_id = @request.env['etna.request_id']
end

Instance Method Details

#erb_partial(name) ⇒ Object



65
66
67
68
# File 'lib/etna/controller.rb', line 65

def erb_partial(name)
  txt = File.read("#{self.class::VIEW_PATH}/#{name}.html.erb")
  ERB.new(txt).result(binding)
end

#erb_view(name) ⇒ Object



70
71
72
73
74
# File 'lib/etna/controller.rb', line 70

def erb_view(name)
  @response['Content-Type'] = 'text/html'
  @response.write(erb_partial(name))
  @response.finish
end

#log(line) ⇒ Object



17
18
19
# File 'lib/etna/controller.rb', line 17

def log(line)
  @logger.warn(request_msg(line))
end

#require_params(*params) ⇒ Object Also known as: require_param

Raises:



39
40
41
42
# File 'lib/etna/controller.rb', line 39

def require_params(*params)
  missing_params = params.reject{|p| @params.key?(p) }
  raise Etna::BadRequest, "Missing param #{missing_params.join(', ')}" unless missing_params.empty?
end

#response(&block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/etna/controller.rb', line 21

def response(&block)
  return instance_eval(&block) if block_given?

  return send(@action) if @action

  [501, {}, ['This controller is not implemented.']]
rescue Etna::Error => e
  @logger.error(request_msg("Exiting with #{e.status}, #{e.message}"))
  return failure(e.status, error: e.message)
rescue Exception => e
  @logger.error(request_msg('Caught unspecified error'))
  @logger.error(request_msg(e.message))
  e.backtrace.each do |trace|
    @logger.error(request_msg(trace))
  end
  return failure(500, error: 'Server error.')
end

#route_path(name, params = {}) ⇒ Object



45
46
47
# File 'lib/etna/controller.rb', line 45

def route_path(name, params={})
  @server.class.route_path(@request, name, params)
end

#route_url(name, params = {}) ⇒ Object



49
50
51
52
53
# File 'lib/etna/controller.rb', line 49

def route_url(name, params={})
  path = route_path(name,params)
  return nil unless path
  @request.scheme + '://' + @request.host + path
end

#view(name) ⇒ Object



58
59
60
61
62
63
# File 'lib/etna/controller.rb', line 58

def view(name)
  txt = File.read("#{self.class::VIEW_PATH}/#{name}.html")
  @response['Content-Type'] = 'text/html'
  @response.write(txt)
  @response.finish
end