Skip to content

Instantly share code, notes, and snippets.

@derekharmel
Created January 3, 2012 21:41
Show Gist options
  • Save derekharmel/1557088 to your computer and use it in GitHub Desktop.
Save derekharmel/1557088 to your computer and use it in GitHub Desktop.
Journaling DSL
module Journaling
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def journals
@journals
end
def journal(method_name, block)
@journals ||= {}
@journals[method_name] = block
class_eval do
alias :"journal_#{method_name}" :"#{method_name}"
end
class_eval <<-METHOD
def #{method_name}(*args)
value = journal_#{method_name}(*args)
journal(:#{method_name}, value)
value
end
METHOD
end
end
def journal(method_name, value)
block = self.class.journals[method_name.to_sym]
return unless block
block.call value
end
end
class JournalTest
include Journaling
def meth1
%w(blank1 blank2 blank3).each do |blank|
end
end
journal :meth1, -> blanks { puts "I ordered #{blanks}" }
end
jt = JournalTest.new
jt.meth1
# => I ordered ["blank1", "blank2", "blank3"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment