Created
October 26, 2010 17:39
-
-
Save samnang/647379 to your computer and use it in GitHub Desktop.
Rubyists are cool! is another example of Ruby metaprogramming.
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
class Person < Struct.new(:name, :programs_ruby) | |
def cool_feeling | |
puts "#{name} is definietly cool!" | |
end | |
end | |
class People < Struct.new(:list) | |
def who | |
SelectQuery.new(self) | |
end | |
def are | |
OutputQuery.new(self) | |
end | |
end | |
class SelectQuery | |
def initialize(people) | |
@people = people | |
end | |
def method_missing(id, *args) | |
@people.list.select! do |p| | |
method_name = id.to_s.gsub!("_", "s_") | |
p.send(method_name, *args) | |
end | |
@people | |
end | |
end | |
class OutputQuery | |
def initialize(people) | |
@people = people | |
end | |
def method_missing(id, *args) | |
@people.list.each { |p| p.send("#{id}_feeling") } | |
@people | |
end | |
end | |
people = People.new([ | |
Person.new("David Heinemeier Hansson", true), | |
Person.new("Bill Gates", false), | |
Person.new("Satish Talim", true), | |
Person.new("Samnang Chhun", true) | |
]) | |
people.who.program_ruby.are.cool |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment