Metaprogramming in Ruby







First Step on Ruby Metaprogramming

First Week

Let's start learning Ruby Metaprogramming!

Please refer our accompanying study notes and examples.







Study 0

1st, review the built-in, read-only variable self. Read the following articles:

self - The current/default object

self - Quote from Programming Ruby 1.9

When does self change? - Quote from The Ruby Object Model

2nd, review singleton class. Read the following article:

3rd, review the scope of variables. Read the following article:





Study 1

To learn about the following methods read The Book of Ruby, Chapter 20: Dynamic Programming.

eval

instance_eval

class_eval (aka: module_eval)

class_variable_set

class_variable_get

class_variables (Try it out: instance_variables)

instance_variable_set (Try it out: instance_variable_get)

define_method

const_set

const_get (Try it out: constants)

Class.new (Try it out: Struct.new)

binding (Try it out: lambda)

send (Try it out: method)

remove_method

undef_method

method_missing





Study 2

Read _why's hacking, Seeing Metaclasses Clearly to learn about the following singleton class (metaclass)

class << self; self; end





Study 3

Read Marc-Andre Cournoyer's blog, Extending your include knowledge of Ruby to learn about the following methods. Also read Ruby-Doc Core API: Module#included and Module#extended

include

extend

included

extended





Before Exercises

Watch the following presentation, the Scotland on Rails conference 2009, by Dave Thomas.

The Ruby Object Model





Exercises

Try to do the following exercises. Let's discuss all these exercises in the relevant thread in the First Week Forum.

Exercise 1: Get the values from outside the class.

Exercise 2: Add your code to display 'I like metaprogramming!'

Exercise 3: Show lots of ways to define singleton method.

Exercise 4: Glance into Ruby inside with binding method.

Exercise 5: Define the class without class and def .





Watch the video

Watch the Dave Thomas's presentation about Metaprogramming.

MetaProgramming - Extending Ruby for Fun and Profit

Understand these concepts:

Classes are open

Definitions are active

All method calls have a receiver

Classes are objects





Cheat Sheet

Cheat Sheet: a list of Ruby metaprogramming techniques







Second Week





Well, let's practice how to write a tiny app with Ruby Metaprogramming techniques.

Note: If you have an idea in your mind. Feel free to please show us and try to do that.





Assignment 1

Define class Dog.





Step 1

There are three dogs named Lassie, Fido and Stimpy.

Look at dog_game.rb. Expected output is the following:

"Lassie is dancing" "Lassie is a smelly doggy!" "Lassie finds this hilarious!" "Fido doesn't understand dance" "Fido is a smelly doggy!" "Fido doesn't understand laugh" "Stimpy is dancing" "Stimpy doesn't understand poo" "Stimpy doesn't understand laugh"

Create dog.rb stored the class Dog.

Hints:

class Dog has three methods: initialize, can, method_missing

may be useful to define the static data like this: MSGS = {:dance => 'is dancing', :poo => 'is a smelly doggy!', :laugh => 'finds this hilarious!'}





Step 2

Challenge: Improve a little bit.

Look at dog_game.rb. Expected output is the following:

"Lassie is dancing" "Lassie is a smelly doggy!" "Lassie finds this hilarious!" "Fido doesn't understand dance" "Fido is smelly." "Fido doesn't understand laugh" "Stimpy is dancing" "Stimpy doesn't understand poo" "Stimpy doesn't understand laugh" "Stimpy cried AHHHH"

Let's improve dog.rb.

Hints:

use can method with block like this: stimpy.can(:cry){"#{name} cried AHHHH"}

method like this: define the name method









Assignment 2

Try to write your own alias_method_chain().





Simple Example

Look at this simple example from Metaprogramming Ruby.

# simple1.rb class MyClass def greet puts "Hello!" end end MyClass.new.greet # => Hello!

Now suppose you want to wrap logging behavior around the above greet(). You can do without editing original code! Look at this:

# simple2.rb require 'simple1' class MyClass def greet_with_log puts "Calling method..." puts "Hello!" puts "...Method called" end alias_method :greeting_with_log, :greet alias_method :greet, :greet_with_log end MyClass.new.greet # => Hello! # Calling method... # Hello! # ...Method called





Generic Metaprogramming Method

Instead of duplicating these aliases all around, let's provide alias_method_chain().

There is the original code rubyist.rb.

# rubyist.rb class Rubyist def initialize name @name = name @count = 0 end def say! puts 'hello' end end





I'd like to add the count feature without editing the original file.

The usage is like this:

# test_snippet.rb require 'rubyist' satish = Rubyist.new('Satish') 3.times{satish.say!} puts '-' * 20 require 'rubyist_with_count' 3.times{satish.say!}





The expected output is this:

hello hello hello -------------------- ***called alias_method_chain*** aliased_target is: say punctuation is: ! Satish(1) starts greeting... hello Satish(1) finished greeting... Satish(2) starts greeting... hello Satish(2) finished greeting... Satish(3) starts greeting... hello Satish(3) finished greeting...

Game

I wrote the following code. Could you please complete it? ;-)





aliasing.rb

# aliasing.rb module RubyLearning module Module def alias_method_chain(target, feature) # write your code here : # # 1. Strip out the final exclamation mark or question mark or equal mark # from the name of the method, to put it at the end of the new aliases. # # 2. If block given, it can pass the aliased method name and punctuation # to the block. # # 3. Alias the methods operation_with_feature() and operation_without_feature(). # # 4. Set the same visibility as original method - private or public or protected # end end end





rubyist_with_count.rb

# rubyist_with_count.rb require 'rubyist' require 'aliasing' class Rubyist extend RubyLearning::Module def say_with_count! # write your code here to show the expected output. end # write your code here to show the expected output. # like this: # # alias_method_chain args do |variables| # bla-bla-bla # end end

Okay, let's discuss your code in the relevant thread in the Second Week Forum. :-D





For More Study





Ruby Metaprogramming Study Note Try to hack the Sample Apps!

Spell Book The excerpt from Metaprogramming Ruby. Collection of Metaprogramming-related small snippets. Useful as a quick reference. For free!





Interesting Articles





Recommended Book

I'd like to highly recommend this book. ;-)







2009.12.20 ashbb

P.S.

Thank you for reading this Ruby Metaprogramming learning guide.

If you are curious, join the Ruby Metaprogramming course on RubyLearning. Details are here.

See you! :-D

This page was last updated on 20th Dec. 2009.