Skip to content

Instantly share code, notes, and snippets.

@Arkham
Created September 7, 2014 00:24
Show Gist options
  • Save Arkham/05ae2957c6b98749c76e to your computer and use it in GitHub Desktop.
Save Arkham/05ae2957c6b98749c76e to your computer and use it in GitHub Desktop.
Respond To Missing
class Person
def initialize(name)
@name = name
end
def small_talk(other)
greet(other)
topics = methods.grep /^chat_about_/
topics.shuffle!
topics.each{ |topic| self.send topic }
end
def greet(other)
puts "Hi #{other}, I'm #{@name}"
end
def chat_about_weather
puts "Hmm.. storm's a coming."
end
def chat_about_sports
puts "Did you see the game last night?"
end
def chat_about_movies
puts "Seen any good movies lately?"
end
def to_s
@name
end
CHAT_METHOD_REGEXP = /^chat_about_(.+)/
def method_missing(name, *arguments)
if name =~ CHAT_METHOD_REGEXP
puts "I don't really know much about #{$1}."
else
super
end
end
def respond_to_missing?(name)
name =~ CHAT_METHOD_REGEXP || super
end
end
class CollectionProxy
include Enumerable
def initialize(collection)
@collection = collection
end
def each(&block)
@collection.each(&block)
end
def to_a
@collection
end
def inspect
details = @collection.inspect
"#<CollectionProxy>: #{details} >"
end
def method_missing(name, *arguments)
mapped_items = @collection.map{ |item| item.send(name, *arguments) }
CollectionProxy.new(mapped_items)
end
def respond_to_missing?(name)
@collection.all?{ |item| item.respond_to? name }
end
end
colors = CollectionProxy.new(%w(red green blue))
p colors.upcase.reverse
numbers = CollectionProxy.new([2, 3, 4])
p numbers + 2
p (numbers + 2).inject(:+)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment