class EasyMvc::Routes

Public Class Methods

new() click to toggle source
# File lib/easymvc/routing.rb, line 3
def initialize
  @routes = []
end

Public Instance Methods

check_url(url) click to toggle source
# File lib/easymvc/routing.rb, line 33
def check_url(url)
  @routes.each do |route|
    match = route[:regexp].match(url)
    if match
      placeholders = {}

      route[:placeholders].each_with_index do |placeholder, index|
        placeholders[placeholder] = match.captures[index]
      end

      if route[:target]
        return convert_target(route[:target])
      else
        controller = placeholders["controller"]
        action = placeholders["action"]
        return convert_target("#{controller}##{action}")
      end
    end
  end
end
convert_target(target) click to toggle source
# File lib/easymvc/routing.rb, line 54
def convert_target(target)
  if target =~ /^([^#]+)#([^#]+)$/
    controller_name = $1.capitalize
    controller = Object.const_get("#{controller_name}Controller")
    controller.action($2)
  end
end
match(url, *args) click to toggle source
# File lib/easymvc/routing.rb, line 7
def match(url, *args)
  target = nil
  target = args.shift if args.size > 0

  url_parts = url.split("/")
  url_parts.select! { |part| !part.empty? }

  placeholders = []
  regexp_parts = url_parts.map do |part|
    if part[0] == ":"
      placeholders << part[1..-1]
      "([A-Za-z0-9_]+)"
    else
      part
    end
  end

  regexp = regexp_parts.join("/")

  @routes << {
      regexp: Regexp.new("^/#{regexp}$"),
      target: target,
      placeholders: placeholders
  }
end