Class: EasyMvc::Controller

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ Controller

Returns a new instance of Controller.



7
8
9
# File 'lib/easymvc/controller.rb', line 7

def initialize(env)
  @request ||= Rack::Request.new(env)
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



5
6
7
# File 'lib/easymvc/controller.rb', line 5

def request
  @request
end

Class Method Details

.action(action_name) ⇒ Object



54
55
56
# File 'lib/easymvc/controller.rb', line 54

def self.action(action_name)
  -> (env) { self.new(env).dispatch(action_name) }
end

Instance Method Details

#controller_nameObject



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

def controller_name
  self.class.to_s.gsub(/Controller$/, "").downcase
end

#dispatch(action) ⇒ Object



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

def dispatch(action)
  content = self.send(action)
  if get_response
    get_response
  else
    render(action)
    get_response
  end
end

#get_responseObject



19
20
21
# File 'lib/easymvc/controller.rb', line 19

def get_response
  @response
end

#paramsObject



11
12
13
# File 'lib/easymvc/controller.rb', line 11

def params
  request.params
end

#render(*args) ⇒ Object



23
24
25
# File 'lib/easymvc/controller.rb', line 23

def render(*args)
  response(render_template(*args))
end

#render_template(view_name, locals = {}) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/easymvc/controller.rb', line 27

def render_template(view_name, locals ={})
  filename = File.join("app", "views", controller_name, "#{view_name}.erb")
  template = File.read(filename)

  vars = {}
  instance_variables.each do |var|
    key = var.to_s.gsub("@", "").to_sym
    vars[key] = instance_variable_get(var)
  end

  Erubis::Eruby.new(template).result(locals.merge(vars))
end

#response(body, status = 200, header = {}) ⇒ Object



15
16
17
# File 'lib/easymvc/controller.rb', line 15

def response(body, status = 200, header = {})
  @response = Rack::Response.new(body, status, header)
end