Class: Radical::Router

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/radical/router.rb

Constant Summary collapse

ACTIONS =
[
  [:index, 'GET', ''],
  [:new, 'GET', '/new'],
  [:show, 'GET', '/:id'],
  [:create, 'POST', ''],
  [:edit, 'GET', '/:id/edit'],
  [:update, 'PUT', '/:id'],
  [:update, 'PATCH', '/:id'],
  [:destroy, 'DELETE', '/:id']
].freeze
RESOURCE_ACTIONS =
[
  [:new, 'GET', '/new'],
  [:create, 'POST', ''],
  [:show, 'GET', ''],
  [:edit, 'GET', '/edit'],
  [:update, 'PUT', ''],
  [:update, 'PATCH', ''],
  [:destroy, 'DELETE', '']
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



62
63
64
# File 'lib/radical/router.rb', line 62

def initialize
  @routes = Hash.new { |hash, key| hash[key] = [] }
end

Instance Attribute Details

#routesObject

Returns the value of attribute routes.



59
60
61
# File 'lib/radical/router.rb', line 59

def routes
  @routes
end

Instance Method Details

#add_resource(klass) ⇒ Object



78
79
80
81
# File 'lib/radical/router.rb', line 78

def add_resource(klass)
  add_routes(klass, actions: RESOURCE_ACTIONS)
  add_resource_paths(klass)
end

#add_resources(klass, parents: nil) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
# File 'lib/radical/router.rb', line 84

def add_resources(klass, parents: nil)
  if parents
    parents.each do |scope|
      add_routes(klass, actions: ACTIONS, scope: scope)
      add_resources_paths(klass, scope: scope)
    end
  else
    add_routes(klass, actions: ACTIONS)
    add_resources_paths(klass)
  end
end

#add_root(klass) ⇒ Object



72
73
74
75
# File 'lib/radical/router.rb', line 72

def add_root(klass)
  add_routes(klass, name: '', actions: ACTIONS)
  add_root_paths(klass)
end

#route(request, options: {}) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/radical/router.rb', line 97

def route(request, options: {})
  params = T.let({}, T.nilable(Hash))

  route = @routes[request.request_method].find do |r|
    params = request.path_info.match(r.first)&.named_captures
  end

  return Rack::Response.new('404 Not Found', 404) unless route

  klass, method = route.last

  params.each do |k, v|
    request.update_param(k, v)
  end

  instance = klass.new(request, options: options)

  response = instance.public_send(method)

  return response if response.is_a?(Rack::Response)

  body = instance.view(method.to_s)

  return Rack::Response.new(nil, 404) if body.nil?

  Rack::Response.new(body, 200, { 'Content-Type' => 'text/html' })
end

#route_prefix(classes) ⇒ Object



67
68
69
# File 'lib/radical/router.rb', line 67

def route_prefix(classes)
  classes.map(&:route_name).map { |n| "#{n}/:#{n}_id" }.join('/')
end