Created
January 6, 2014 19:46
-
-
Save slant/8288657 to your computer and use it in GitHub Desktop.
Experimenting with metaprogramming in Ruby.
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 Thing | |
def self.format_answer_for(question_title, &block) | |
define_method("__format_answer_for_#{question_title}", &block) | |
end | |
end | |
################# | |
## Test Case 1 ## | |
################# | |
# Define a new instance method using an arbitrary string ("testing") | |
Thing.format_answer_for("testing") { puts "O HAI" } | |
# Call the method directly | |
Thing.new.__format_answer_for_testing # O HAI | |
################# | |
################# | |
## Test Case 2 ## | |
################# | |
# Define another new instance method, store it | |
thing = Thing.format_answer_for("another") { puts "WAT" } | |
# Output instance methods for class Thing | |
puts Thing.instance_methods - Object.methods # __format_answer_for_another | |
# Call the new instance method | |
thing.call # WAT | |
################# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment