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

params() click to toggle source

Stores parameters created when variable_route? finds a match.

# File lib/cubic/router.rb, line 28
def params
  @param ||= {}
end
routes() click to toggle source

Stores all of the routes for the application.

# File lib/cubic/router.rb, line 10
def routes
  @route ||= []
end
set_route(http_method, route, block) click to toggle source

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

check_variable_routes(url, http) click to toggle source

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
create_param(key, value) click to toggle source

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
root_path?(url) click to toggle source
# File lib/cubic/router.rb, line 34
def root_path?(url)
  url == '/' ? 'index' : url
end
route_parser(route, url) click to toggle source

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
to_symbole(string) click to toggle source

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?(route, url) click to toggle source

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