Module: Happy::Controller::Routing
- Included in:
- Happy::Controller
- Defined in:
- lib/happy/controller/routing.rb
Instance Method Summary collapse
Instance Method Details
#on(*args, &blk) ⇒ 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 40 |
# File 'lib/happy/controller/routing.rb', line 10 def on(*args, &blk) = (args.pop if args.last.is_a?(Hash)) || {} args = [nil] if args.empty? args.each do |name| # If a path name has been given, match it against the next request path part. if name.present? # convert symbols to ":foo" type string name = ":#{name}" if name.is_a?(Symbol) path_match = path_to_regexp(name).match(unprocessed_path.first) end # Match the request method, if specified method_matched = [nil, request.request_method.downcase.to_sym].include?([:method]) path_matched = (path_match || (name.nil? && unprocessed_path.empty?)) # Only do something here if method and requested path both match if path_matched && method_matched # Transfer variables contained in path name to params hash if path_match name.scan(/:(\w+)/).flatten.each do |var| request.params[var] = path_match.captures.shift end processed_path << unprocessed_path.shift end serve!(instance_exec(&blk)) or raise Errors::NotFound end end end |
#path_to_regexp(path) ⇒ Object
4 5 6 7 8 |
# File 'lib/happy/controller/routing.rb', line 4 def path_to_regexp(path) # Since we want to be compatible with Ruby 1.8.7, we unfortunately can't use named captures like this: # Regexp.compile('^'+path.gsub(/\)/, ')?').gsub(/\//, '\/').gsub(/\./, '\.').gsub(/:(\w+)/, '(?<\\1>.+)')+'$') Regexp.compile('^'+path.gsub(/\)/, ')?').gsub(/\//, '\/').gsub(/\./, '\.').gsub(/:(\w+)/, '(.+)')+'$') end |