Created
October 19, 2012 05:15
-
-
Save jeremywrowe/3916364 to your computer and use it in GitHub Desktop.
Fun with delegation / blocks
This file contains 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
require 'delegate' | |
class Router | |
def match(path, &block) | |
puts "match: #{path}" | |
puts instance_eval(&block) if block_given? | |
end | |
def resource(name, &block) | |
puts "resource: #{name}" | |
instance_eval(&block) if block_given? | |
end | |
def scope(name, &block) | |
puts "scope: #{name}" | |
instance_eval(&block) if block_given? | |
end | |
def namespace(name, &block) | |
puts "namespace: #{name}" | |
instance_eval(&block) if block_given? | |
end | |
def resources(*res, &block) | |
@a ||= {} | |
@first ||= true | |
@count ||= 1 | |
resp = res.join(', ') | |
@a[@count] = resp | |
if block_given? | |
@count += 1 | |
instance_eval(&block) | |
end | |
if @a.any? && @first | |
@first = false | |
@count.times do |t| | |
t = t+1 | |
puts "\t"*t + "|__" + @a[t] if @a[t] | |
end | |
end | |
resp | |
end | |
end | |
class Extender < DelegateClass(Router) | |
def initialize(router=Router.new) | |
@delegate = router | |
super(@delegate) | |
end | |
def define_routes(&block) | |
instance_eval(&block) if block_given? | |
end | |
end | |
class FellowExtender < Extender | |
def define_routes(&block) | |
super(&block) | |
end | |
end | |
ext = FellowExtender.new | |
ext.define_routes do | |
scope "farts" do | |
resources :shoes, :sandles do | |
resources :frank, :sinatra do | |
resources :red, :ridding_hood | |
resources :red2, :ridding_hood2 | |
resources :red3, :ridding_hood3 | |
resources :red4, :ridding_hood4 | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment