class WebRouter::Router
Attributes
routes[R]
Public Class Methods
new()
click to toggle source
# File lib/web_router/router.rb, line 14 def initialize @routes = [] end
Public Instance Methods
call(env)
click to toggle source
# File lib/web_router/router.rb, line 2 def call(env) find_route(env).call(env) end
configure(&block)
click to toggle source
# File lib/web_router/router.rb, line 6 def configure(&block) instance_exec(&block) self end
Private Instance Methods
delete(path, rack_app)
click to toggle source
# File lib/web_router/router.rb, line 21 def delete(path, rack_app) match('DELETE', path, rack_app) end
extract_params(pattern, path)
click to toggle source
pattern: “post/:name”, route: “post/about_ruby”
# File lib/web_router/router.rb, line 57 def extract_params(pattern, path) pattern .split('/') # ['post', ':name'] .zip(path.split('/')) # [['post', 'post'],[':name', 'post']] .reject { |e| e.first == e.last } # [[':name', 'post']] .map { |e| [e.first[1..-1], e.last] } # [['name', 'post']] .to_h end
find_route(env)
click to toggle source
# File lib/web_router/router.rb, line 41 def find_route(env) routes.each do |route| if env['REQUEST_METHOD'] == route[:method] && env['REQUEST_PATH'] =~ route[:regexp] env['router.params'] = extract_params(route[:pattern], env['REQUEST_PATH']) return route[:app] end end ->(_env) { [404, {}, ['not found']] } end
get(path, rack_app)
click to toggle source
# File lib/web_router/router.rb, line 18 def get(path, rack_app) match('GET', path, rack_app) end
get_controller_action(str)
click to toggle source
# File lib/web_router/router.rb, line 28 def get_controller_action(str) controller_name, action_name = str.split('#') # tests#show => ['tests', 'show'] controller_name = to_upper_camel_case(controller_name) Kernel.const_get(controller_name).send(:action, action_name) end
match(http_method, path, rack_app)
click to toggle source
# File lib/web_router/router.rb, line 23 def match(http_method, path, rack_app) rack_app = get_controller_action(rack_app) if rack_app.is_a? String routes << { pattern: path, app: rack_app, regexp: path_to_regexp(path), method: http_method} end
path_to_regexp(path)
click to toggle source
# File lib/web_router/router.rb, line 52 def path_to_regexp(path) Regexp.new('\A' + path.gsub(/:[\w-]+/, '[\w-]+') + '\Z') end
post(path, rack_app)
click to toggle source
# File lib/web_router/router.rb, line 19 def post(path, rack_app) match('POST', path, rack_app) end
put(path, rack_app)
click to toggle source
# File lib/web_router/router.rb, line 20 def put(path, rack_app) match('PUT', path, rack_app) end
to_upper_camel_case(str)
click to toggle source
# File lib/web_router/router.rb, line 34 def to_upper_camel_case(str) str # 'public_pages/tests' => PublicPages::TestsController .split('/') # ['public_pages', 'test'] .map { |part| part.split('_').map(&:capitalize).join } # ['PublicPages', 'Test'] .join('::') + 'Controller' end