Skip to content

Instantly share code, notes, and snippets.

@delbetu
Created December 10, 2016 20:44
Show Gist options
  • Save delbetu/13a07aee001eb78fc8ce3c6b3501270a to your computer and use it in GitHub Desktop.
Save delbetu/13a07aee001eb78fc8ce3c6b3501270a to your computer and use it in GitHub Desktop.
Ruby meta programming example. define_method, instance_eval, blocks
Mailer.deliver do 
  from    "eki@eqbalq.com"
  to      "jill@example.com"
  subject "Threading and Forking"
  body    "Some content"
end

This code can be implemented like it's shown below.

class Mailer

  def self.deliver(&block)
    mail = MailBuilder.new(&block).mail
    mail.send_mail
  end

  Mail = Struct.new(:from, :to, :subject, :body) do 
    def send_mail
      puts "Email from: #{from}"
      puts "Email to  : #{to}"
      puts "Subject   : #{subject}"
      puts "Body      : #{body}"
    end
  end

  class MailBuilder
    def initialize(&block)
      @mail = Mail.new
      instance_eval(&block) #Execute passed block in this context
    end
    
    attr_reader :mail

    %w(from to subject body).each do |m|
      define_method(m) do |val|
        @mail.send("#{m}=", val)
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment