Skip to content

Instantly share code, notes, and snippets.

@digitarald
Forked from Mikoangelo/router.rb
Created September 26, 2008 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitarald/13092 to your computer and use it in GitHub Desktop.
Save digitarald/13092 to your computer and use it in GitHub Desktop.
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