Skip to content

Instantly share code, notes, and snippets.

@mtodd
Created June 20, 2010 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mtodd/445605 to your computer and use it in GitHub Desktop.
Save mtodd/445605 to your computer and use it in GitHub Desktop.
module Enumerable
def each_with_context(&block)
block.call([nil, self[0], self[1]])
self.each_cons(3, &block)
block.call([self[self.size - 2], self[self.size - 1], nil])
self
end
def enum_with_context
Enumerable::Enumerator.new(self, :each_with_context)
end
end
require 'rubygems'
require 'activesupport'
class User < Struct.new(:id, :name)
def self.find(n); self.new(n, "Matt"); end
end
class Post < Struct.new(:id, :name)
def self.find(n); self.new(n, "HooHah"); end
end
class Comment < Struct.new(:id, :name)
def self.find(n); self.new(n, "Sweet"); end
end
url = "users/1/posts/2/comments/3"
url.split('/').each_with_context do |(prev, element, _)|
case element
when /^\d+$/
p [:element, prev.singularize.camelize.constantize.find(element).name]
else
p [:element, element]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment