Skip to content

Instantly share code, notes, and snippets.

@samnang
Created October 26, 2010 17:39
Show Gist options
  • Save samnang/647379 to your computer and use it in GitHub Desktop.
Save samnang/647379 to your computer and use it in GitHub Desktop.
Rubyists are cool! is another example of Ruby metaprogramming.
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