Created
May 5, 2011 19:18
-
-
Save oem/957699 to your computer and use it in GitHub Desktop.
small excercise to refresh some metaprogramming stuff
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
# just a small refresher on some meta stuff - haven't commited all of it to | |
# muscle memory yet | |
class NoteBook | |
attr_accessor :notes | |
class << self | |
attr_accessor :subclasses | |
end | |
@subclasses = [] | |
def self.inherited(subclass) | |
NoteBook.subclasses << subclass | |
end | |
def self.note(desc, *args, &block) | |
name = "note_" + desc.gsub(/\s+/, "_").downcase | |
define_method(name, *args) do | |
@notes += "# #{desc}\n\n" | |
instance_eval(&block) | |
@notes += "\n\n" | |
end | |
end | |
def initialize | |
@notes = "" | |
end | |
def content(text) | |
@notes += "#{text}\n\n" | |
end | |
def footer(text) | |
@notes += "#{text}" | |
end | |
end | |
at_exit do | |
all_notes = "" | |
NoteBook.subclasses.each do |subclass| | |
sub = subclass.new | |
subclass.instance_methods(false).each do |meth| | |
sub.send(meth) if meth.to_s =~ /^note/ | |
end | |
all_notes += sub.notes | |
end | |
puts all_notes | |
end | |
# use it like this: | |
class Book < NoteBook | |
note "dear diary..." do | |
content "no comment" | |
footer "seriously, go away. Stop stalking me you pesky book" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment