Class: Zephyre::Router
Instance Method Summary collapse
- #check_url(url, method) ⇒ Object
- #convert_target(target) ⇒ Object
- #create_http_methods ⇒ Object
-
#initialize ⇒ Router
constructor
A new instance of Router.
Constructor Details
#initialize ⇒ Router
Returns a new instance of Router.
4 5 6 7 8 |
# File 'lib/zephyre/routing.rb', line 4 def initialize @routes = [] create_http_methods end |
Instance Method Details
#check_url(url, method) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/zephyre/routing.rb', line 41 def check_url(url, method) @routes.each do |route| match = route[:regexp].match(url) if (match && (route[:method] == "MATCH" || route[:method].match(method))) 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) ⇒ Object
64 65 66 67 68 69 70 |
# File 'lib/zephyre/routing.rb', line 64 def convert_target(target) if target =~ /^([^.]+).([^.]+)$/ controller_name = $1.to_camel_case controller = Object.const_get("#{controller_name}Controller") return controller.action($2) end end |
#create_http_methods ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/zephyre/routing.rb', line 10 def create_http_methods [:get, :post, :put, :patch, :delete, :match].each do |http_method| self.define_singleton_method(http_method) do |pathmap| target = pathmap.values.first url_parts = pathmap.keys.first.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, method: "#{http_method.to_s.upcase}" } end end end |