class Algernon::Routing::Router

Constants

HTTP_VERBS

Attributes

part_regex[RW]
routes[RW]
url_placeholders[RW]

Public Class Methods

new() click to toggle source
# File lib/algernon/routing/router.rb, line 12
def initialize
  @routes = {}
  @url_placeholders = {}
  @part_regex = []
  http_verb_creator
end

Public Instance Methods

convert_regex_parts_to_path(regex_match) click to toggle source
# File lib/algernon/routing/router.rb, line 75
def convert_regex_parts_to_path(regex_match)
  regex_string = "^" + regex_match.join("/") + "/*$"
  Regexp.new(regex_string)
end
draw(&block) click to toggle source
# File lib/algernon/routing/router.rb, line 19
def draw(&block)
  instance_eval(&block)
end
extract_regex_and_placeholders(path) click to toggle source
# File lib/algernon/routing/router.rb, line 54
def extract_regex_and_placeholders(path)
  path.path_format!

  @part_regex = []
  @url_placeholders = {}
  path.split("/").each_with_index do |path_part, index|
    store_part_and_placeholder(path_part, index)
  end

  [part_regex, url_placeholders]
end
get_match(http_verb, path) click to toggle source
# File lib/algernon/routing/router.rb, line 27
def get_match(http_verb, path)
  http_verb = http_verb.downcase
  routes[http_verb].detect do |route|
    route.check_path(path)
  end
end
has_routes?() click to toggle source
# File lib/algernon/routing/router.rb, line 23
def has_routes?
  routes.any?
end
http_verb_creator() click to toggle source
# File lib/algernon/routing/router.rb, line 34
def http_verb_creator
  self.class.class_eval do
    HTTP_VERBS.each do |http_verb|
      define_method(http_verb) do |path, to:|
        process_and_store_route(http_verb, path, to)
      end
    end
  end
end
process_and_store_route(http_verb, path, to) click to toggle source
# File lib/algernon/routing/router.rb, line 44
def process_and_store_route(http_verb, path, to)
  regex_parts, url_placeholders = extract_regex_and_placeholders(path)
  path_regex = convert_regex_parts_to_path(regex_parts)
  route_object = Algernon::Routing::Finder.new(
    path_regex, to, url_placeholders
  )
  routes[http_verb.downcase.freeze] ||= []
  routes[http_verb.downcase] << route_object
end
store_part_and_placeholder(path_part, index) click to toggle source
# File lib/algernon/routing/router.rb, line 66
def store_part_and_placeholder(path_part, index)
  if path_part.start_with?(":")
    url_placeholders[index] = path_part.delete(":").freeze
    part_regex << "[a-zA-Z0-9_]+"
  else
    part_regex << path_part
  end
end