class Cubic::Router
Handles whether or not the path, given by Rack::Request, matches any of the routes defined within the application.
Public Class Methods
Stores parameters created when variable_route? finds a match.
# File lib/cubic/router.rb, line 28 def params @param ||= {} end
Stores all of the routes for the application.
# File lib/cubic/router.rb, line 10 def routes @route ||= [] end
Searches url against defined routes. If none are found, we check if the url fits the pattern of a route containing variables.
# File lib/cubic/router.rb, line 21 def search(http, url) url = root_path?(url) route = routes.find { |i| i[:http_method] == http && i[:route] == url } route ? route : check_variable_routes(url, http) end
Adds a route to the routes array.
# File lib/cubic/router.rb, line 15 def set_route(http_method, route, block) routes << { http_method: http_method, route: route, block: block } end
Private Class Methods
Checks all routes that may have a variable; e.g. /post/:variable
# File lib/cubic/router.rb, line 53 def check_variable_routes(url, http) routes.find do |i| i[:http_method] == http && variable_route?(i[:route], url) end end
Creates a hash of parameters from variables supplied in the url and merges them into the params hash given by Rack::Request.
# File lib/cubic/router.rb, line 40 def create_param(key, value) return params[to_symbole(key)] = value.to_i if value.integer? params[to_symbole(key)] = value end
# File lib/cubic/router.rb, line 34 def root_path?(url) url == '/' ? 'index' : url end
Checks if route can be turned into a variable.
# File lib/cubic/router.rb, line 74 def route_parser(route, url) if route.include?(':') create_param(route, url) elsif route == url true else false end end
Turns a string preceeded by a colon into a symbole. ':id'.to_sym would result in ::id, so we must remove any colons first.
# File lib/cubic/router.rb, line 48 def to_symbole(string) string.delete(':').to_sym end
variable_route? compares all routes against the url again, but allows the url to fit into a 'variable route' if one is found that matches the url pattern.
# File lib/cubic/router.rb, line 62 def variable_route?(route, url) route = route.split('/').reject(&:empty?) url = url.split('/').reject(&:empty?) after = route.zip(url).map do |r, u| r.nil? || u.nil? ? false : route_parser(r, u) end after.include?(false) ? false : true end