Class: Yescode::Router

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

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(routes) ⇒ Router

Returns a new instance of Router.



15
16
17
18
# File 'lib/yescode/router.rb', line 15

def initialize(routes)
  @routes = routes
  @logger = self.class.logger
end

Class Attribute Details

.assetsObject

Returns the value of attribute assets.



12
13
14
# File 'lib/yescode/router.rb', line 12

def assets
  @assets
end

.loggerObject

Returns the value of attribute logger.



12
13
14
# File 'lib/yescode/router.rb', line 12

def logger
  @logger
end

Instance Method Details

#call(env) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/yescode/router.rb', line 20

def call(env)
  path_info = env[Rack::PATH_INFO]
  request_method = env[Rack::REQUEST_METHOD]
  params = {}
  route = @routes[request_method].find do |r|
    path = Regexp.new("^#{r.first.gsub(/:(\w+)/, '(?<\1>[a-zA-Z0-9_\-=]+)')}$")
    params = path_info.match(path)&.named_captures
  end

  raise RouteNotFound unless route

  params.merge!(env[Rack::RACK_REQUEST_FORM_HASH] || {})
        .transform_keys!(&:to_sym)
  env["params"] = params
  _, class_name, method = route
  klass = nil
  begin
    klass = Object.const_get(class_name)
  rescue NameError => e
    raise RouteClassDoesNotExist, e.message
  end
  controller = klass.new(env)
  raise RouteMethodDoesNotExist, "#{class_name}##{method} does not exist" unless controller.respond_to?(method)

  @logger&.info(msg: "Request dispatched", route: "#{class_name}##{method}", params: params.except(:_csrf))
  klass.assets = self.class.assets
  klass.before_actions&.each do |before_action|
    controller.send(before_action)
  end
  response = controller.public_send(method)
  raise NotFoundError if response.nil?

  case response
  when YesView
    controller.render response
  else
    response
  end
rescue NotFoundError, RouteNotFound
  raise if Env.development?

  [404, { "content-type" => "text/html" }, File.open("public/404.html")]
rescue StandardError
  raise if Env.development?

  [500, { "content-type" => "text/html" }, File.open("public/500.html")]
end