Thursday, February 3, 2011

actionmailer has a neat trick

to turn some code i wrote into a gem, i decided to read through other gems for examples of how to do it. while reading through the actionmailer gem installed with rails 3.0.3, i found this /home/ozzloy/.rvm/gems/ruby-1.9.2-p136@rails3tutorial/gems/actionmailer-3.0.3/lib/rails/generators/mailer/templates/mailer.rb:

class <%= class_name %> < ActionMailer::Base
default :from => "from@example.com"
<% for action in actions -%>

# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.<%= file_path.gsub("/",".") %>.<%= action %>.subject
#
def <%= action %>
@greeting = "Hi"

mail :to => "to@example.org"
end
<% end -%>
end

so that's cool! it's using ruby to generate ruby code. metaprogramming, but not by manipulating classes and modules directly. instead generating the source code to create modules and classes, which i presume gets printed to a file with scaffolding. and probably also eval'd so as to keep DRY. anyways, neat.

No comments:

Post a Comment

Where am I?