-
-
Save digitarald/13092 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Murray | |
class Router | |
class << self | |
attr_reader :mapping | |
def map &block | |
@mapping = [] | |
instance_eval &block | |
self | |
end | |
def method_missing meth, &block | |
super unless meth.to_s[0,1] =~ /[A-Z]/ | |
@mapping << Scope.new(meth, &block) | |
end | |
def describe | |
@mapping.each do |scope| | |
puts "#{scope.name}:" | |
scope.contents.each do |flake| | |
puts "\t+ /#{flake.to_path}" | |
end | |
puts "\n" | |
end | |
end | |
end | |
class Scope | |
undef :id | |
attr_accessor :name, :contents | |
def initialize name, &block | |
@name = name | |
@contents = [] | |
instance_eval &block | |
end | |
def method_missing meth, *args, &block | |
super if meth.to_s[0,1] =~ /[A-Z]/ | |
case args.length | |
when 0 | |
Flake.new self, meth | |
when 1 | |
Parameter.new meth, args.first | |
else | |
super | |
end | |
end | |
def f name | |
Flake.new self, name | |
end | |
def << flake | |
@contents << flake | |
end | |
def inspect | |
"#<Scope " + @contents.join(', ') + ">" | |
end | |
end | |
class Flake | |
attr_reader :contents | |
def initialize scope, first | |
@scope = scope | |
@contents = [first] | |
end | |
def / other | |
if Flake === other | |
@contents.concat other.contents | |
else | |
@contents << other | |
end | |
self | |
end | |
def +@ | |
@scope << self | |
end | |
def inspect | |
"#<Flake #{@contents.join('/')}>" | |
end | |
alias_method :to_s, :inspect | |
def to_path | |
"#{@contents.map{|f| Symbol === f ? f.to_s : f.to_path}.join('/')}" | |
end | |
end | |
class Parameter | |
attr_reader :name, :type | |
def initialize name, type | |
@name, @type = name, type | |
end | |
def to_path | |
":#@name" | |
end | |
def inspect | |
"(#@name #@type)" | |
end | |
alias_method :to_s, :inspect | |
end | |
end | |
end | |
if $0 == __FILE__ | |
Murray::Router.map do | |
Establishments do | |
+ (list / (zip_code:integer)) # "http://example.org/establishments/2639" | |
+ (index / (id:integer) / bar / (foo:array)) | |
+ (show / (short_name:string)) | |
end | |
People do | |
+(show / (guy:integer)) | |
end | |
end | |
Murray::Router.describe | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment