class Pup::Routing::Router

Constants

ALLOWED_VERBS

Attributes

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

Public Class Methods

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

Public Instance Methods

create(&block) click to toggle source
# File lib/pup/routing/router.rb, line 19
def create(&block)
  instance_eval(&block)
end
get_match(verb, path) click to toggle source
# File lib/pup/routing/router.rb, line 27
def get_match(verb, path)
  verb = verb.downcase
  routes[verb].detect do |route|
    route.check_path(path)
  end
end
has_routes?() click to toggle source
# File lib/pup/routing/router.rb, line 23
def has_routes?
  true unless routes.empty?
end

Private Instance Methods

convert_regex_parts_to_path(regex_match) click to toggle source
# File lib/pup/routing/router.rb, line 74
def convert_regex_parts_to_path(regex_match)
  regex_string = "^" + regex_match.join("/") + "/*$"
  Regexp.new(regex_string)
end
extract_regex_and_placeholders(path) click to toggle source
# File lib/pup/routing/router.rb, line 53
def extract_regex_and_placeholders(path)
  path.sanitize_path!

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

  [part_regex, url_placeholders]
end
generate_verb_methods() click to toggle source
# File lib/pup/routing/router.rb, line 34
def generate_verb_methods
  self.class.instance_eval do
    ALLOWED_VERBS.each do |verb|
      define_method(verb) do |path, to:|
        process_and_store_route(verb, path, to)
      end
    end
  end
end
process_and_store_route(verb, path, to) click to toggle source
# File lib/pup/routing/router.rb, line 44
def process_and_store_route(verb, path, to)
  regex_parts, url_placeholders = extract_regex_and_placeholders(path)
  path_regex = convert_regex_parts_to_path(regex_parts)
  route_object = Pup::Routing::Route.new(path_regex, to, url_placeholders)

  routes[verb.downcase.freeze] ||= []
  routes[verb.downcase] << route_object
end
store_part_and_placeholder(path_part, index) click to toggle source
# File lib/pup/routing/router.rb, line 65
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