Forked from bryanwoods/ruby_metaprogramming_example_engibeering.rb
Created
January 18, 2013 22:08
-
-
Save oggy/4569070 to your computer and use it in GitHub Desktop.
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
class Person | |
attr_reader :full_name, :age, :profession, :favorite_food | |
def initialize(full_name, age, profession, favorite_food) | |
@full_name = full_name | |
@age = age | |
@profession = profession | |
@favorite_food = favorite_food | |
end | |
end | |
class People | |
attr_reader :people, :attributes | |
def initialize(people) | |
@people = people | |
@attributes = define_attributes | |
define_dynamic_finders | |
end | |
private | |
def define_attributes | |
people.map do |person| | |
person.instance_variables.map(&:to_s).map do |attribute| | |
attribute.gsub("@", "") | |
end | |
end.flatten.uniq | |
end | |
def define_dynamic_finders | |
attributes.each do |attribute| | |
self.class.class_eval do | |
define_method("find_by_#{attribute}") do |argument| | |
people.select { |person| person.send(attribute) == argument } | |
end | |
end | |
end | |
end | |
end | |
group = People.new([ | |
Person.new("Bryan Woods", 27, :programmer, "sushi"), | |
Person.new("Kurt Cobain", 27, :musician, "apple pie"), | |
Person.new("Shawn Carter", 43, :musician, "pizza"), | |
Person.new("Jonathan Franzen", 53, :author, "macaroni and cheese") | |
]) | |
musicians = group.find_by_profession(:musician) | |
musicians.each { |musician| puts "#{musician.full_name} is a musician!" } | |
twenty_seven_year_olds = group.find_by_age(27) | |
twenty_seven_year_olds.each do |person| | |
puts "#{person.full_name} is #{person.age} and loves #{person.favorite_food}!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment