Class: Eksa::Application

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Application

Returns a new instance of Application.

Yields:

  • (_self)

Yield Parameters:



10
11
12
13
14
15
16
17
18
# File 'lib/eksa.rb', line 10

def initialize
  @routes = {}
  @middlewares = []
  @config = {
    db_path: File.expand_path("./db/eksa_app.db")
  }
  yield self if block_given?
  configure_framework
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/eksa.rb', line 8

def config
  @config
end

#middlewaresObject (readonly)

Returns the value of attribute middlewares.



8
9
10
# File 'lib/eksa.rb', line 8

def middlewares
  @middlewares
end

Instance Method Details

#add_route(path, controller_class, action) ⇒ Object



24
25
26
# File 'lib/eksa.rb', line 24

def add_route(path, controller_class, action)
  @routes[path] = { controller: controller_class, action: action }
end

#build_appObject



37
38
39
40
41
42
43
44
# File 'lib/eksa.rb', line 37

def build_app
  builder = Rack::Builder.new
  @middlewares.each do |middleware, args, block|
    builder.use(middleware, *args, &block)
  end
  builder.run(method(:core_call))
  builder.to_app
end

#call(env) ⇒ Object



32
33
34
35
# File 'lib/eksa.rb', line 32

def call(env)
  @app ||= build_app
  @app.call(env)
end

#configure_frameworkObject



20
21
22
# File 'lib/eksa.rb', line 20

def configure_framework
  Eksa::Model.database_path = @config[:db_path]
end

#core_call(env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/eksa.rb', line 46

def core_call(env)
  request = Rack::Request.new(env)
  flash_message = request.cookies['eksa_flash']
  route = @routes[request.path_info]

  if route
    controller_instance = route[:controller].new(request)
    controller_instance.flash[:notice] = flash_message if flash_message
    response_data = controller_instance.send(route[:action])
    if response_data.is_a?(Array) && response_data.size == 3
      status, headers, body = response_data
      response = Rack::Response.new(body, status, headers)
    else
      response = Rack::Response.new
      if controller_instance.status == 302
        response.redirect(controller_instance.redirect_url, 302)
      else
        response.write(response_data)
        response['content-type'] = 'text/html'
      end
    end

    response.delete_cookie('eksa_flash') if flash_message
    response.finish
  else
    [404, { 'content-type' => 'text/html' }, ["<div style='font-family:sans-serif; text-align:center; padding-top:50px;'><h1>404</h1><p>Halaman tidak ditemukan di Eksa Framework.</p></div>"]]
  end
end

#use(middleware, *args, &block) ⇒ Object



28
29
30
# File 'lib/eksa.rb', line 28

def use(middleware, *args, &block)
  @middlewares << [middleware, args, block]
end