Skip to content

Instantly share code, notes, and snippets.

@andreypopp
Last active December 20, 2015 04:19
Show Gist options
  • Save andreypopp/6069936 to your computer and use it in GitHub Desktop.
Save andreypopp/6069936 to your computer and use it in GitHub Desktop.
require 'json'
require 'uri_template'
require 'scorched'
class Controller < Scorched::Controller
include Scorched::Options('uri_templates')
##
# Generate URI out of the template
#
def uri(name, **vars)
paths = request.breadcrumb[0..-2].map { |x| x[:path] }
template = uri_templates[name] or URITemplate.new(name)
url "#{paths.join}#{template.expand(vars)}"
end
class << self
##
# Mount another controller under prefix
#
def mount(prefix, controller)
controller.config[:auto_pass] = true if controller.is_a? Class and controller < Controller
self << {pattern: prefix, target: controller}
end
##
# Define named URI template for the controller
#
def uri(name, template)
template = URITemplate.new(template) unless template.is_a? URITemplate
uri_templates << { name => template }
end
private
def compile(pattern, match_to_end = false)
pattern = uri_templates[pattern] || pattern
if pattern.is_a? URITemplate then
pattern
else
super(pattern, match_to_end)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment