Class: Rubee::Router

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/rubee/router.rb

Constant Summary collapse

HTTP_METHODS =
%i[get post put patch delete head connect options trace].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



7
8
9
# File 'lib/rubee/router.rb', line 7

def request
  @request
end

#routesObject (readonly)

Returns the value of attribute routes.



7
8
9
# File 'lib/rubee/router.rb', line 7

def routes
  @routes
end

Class Method Details

.draw {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (Rubee::Router)

    the object that the method was called on



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

def draw
  yield(self) if block_given?
end

.route_for(request) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/rubee/router.rb', line 16

def route_for(request)
  method = (request.params['_method'] || request.request_method).downcase.to_sym
  @routes.find do |route|
    return route if request.path == route[:path] && request.request_method&.downcase&.to_sym == route[:method]

    pattern = route[:path].gsub(/{.*?}/, '([^/]+)')
    regex = /^#{pattern}$/
    regex.match?(request.path) && method.to_s == route[:method].to_s
  end
end

.set_route(path, to:, method: __method__, **args) ⇒ Object



27
28
29
30
31
# File 'lib/rubee/router.rb', line 27

def set_route(path, to:, method: __method__, **args)
  controller, action = to.split('#')
  @routes.delete_if { |route| route[:path] == path && route[:method] == method }
  @routes << { path:, controller:, action:, method:, **args }
end