Your SlideShare is downloading. ×
0
Metaprogramingin RubyBrian Sam-Bodden
What’s this all about?‣ We’ll learn...‣ mainly about Ruby’s Meta-programming power‣ about a language doesn’t treat you lik...
Ruby
Ruby Ideals:Programming should be fun!“I believe people want to express themselves when theyprogram.They don’t want to figh...
Ruby
Rubyis...
Rubyis...✓Object-Oriented
Rubyis...✓Object-Oriented✓General Purpose
Rubyis...✓Object-Oriented✓ Interpreted✓General Purpose
Rubyis...✓Object-Oriented✓Dynamic✓ Interpreted✓General Purpose
Rubyis...✓Object-Oriented✓Dynamic✓ Interpreted✓General Purpose✓ Garbage-collected
Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Garbage-collected
Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Multi-paradigm✓ Garbage-collected
Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Multi-paradigm✓ Garbage-collected✓Elegant
Without Ruby there would beno RailsRuby’s meta-programing is the keyfeature that makes Rails magical
OpenClasses
Say we have an Array like:
Say we have an Array like:[1,2,3,4,5]
Say we have an Array like:[1,2,3,4,5]and we want to sum ofall of its elements
Let’s try something like:
Let’s try something like:[1,2,3,4,5].sum
Let’s try something like:[1,2,3,4,5].sum
Let’s try something like:[1,2,3,4,5].sumRats! Doesn’t work in Ruby
Let’s try something like:[1,2,3,4,5].sumRats! Doesn’t work in Ruby… yet!
Ruby classes are
Ruby classes are
Ruby classes areWe can teach the Array class a new behavior
Ruby classes areWe can teach the Array class a new behavior
Let’s try again!
Let’s try again!
Let’s try again!All you need to do is load the filecontaining the enhancements
Code asDataBend at will your code should
When code can be manipulated as dataa whole world of possibilities opensIn Ruby you can evaluate thecontents of a string
Code that invokes code,that invokes code
Code that invokes code,that invokes code
Code that invokes code,that invokes codeThere you go, there you go
Ruby provides the eval family ofmethods for runtime execution ofcode stored in strings
Ruby provides the eval family ofmethods for runtime execution ofcode stored in strings
Ruby provides the eval family ofmethods for runtime execution ofcode stored in stringseval will evaluate any string
instance_eval can evaluate astring or a code block
instance_eval can evaluate astring or a code block
instance_eval can evaluate astring or a code blockin the context of the receiver
class_eval can evaluate a string or a code blockin the context of the class or module it is called on
class_eval can evaluate a string or a code blockin the context of the class or module it is called on
In Ruby we try to think about sending a message toan object rather than calling a method on an object
In Ruby we try to think about sending a message toan object rather than calling a method on an objectIn simple cases (abov...
Meta-programming
...is about programs thatwrite programsMeta-programming...it’s a superb tool for buildingframeworks...it’s the key ingredi...
Ruby’s is a great vehicle formeta-programming because it is:dynamic and reflexiveopen and malleableclean syntaxcode is data...
...uses meta-programming to bringthe language closer to the problem...is a collection of domain-specificlanguages (DSL) for...
SingletonClass
In Ruby you can enhance aparticular instance of a classRuby uses a proxy class known asthe singleton classMeta-class:The s...
class_eval indirectly uses the meta-classadding a singleton method to the class
Rails relies heavily on Ruby’s abilityto dynamically enhance a class
Rails relies heavily on Ruby’s abilityto dynamically enhance a class
Shortcuts such as define_methodexist to make life easier
Accessing the singleton meta-classexplicitly
Child classes get enhanced withclass methods
Inheritancethe Ruby Way
Many Ruby DSLs create classmethods on subclasses using themeta-class (singleton class)
Rails uses this technique in ActiveRecord
A module with a “Base” class
Methods get added to our classes withsimple declarationsGetting closer to a DSL!
Now our class has a new set of classmethods
Now our class has a new set of classmethods
AOPthe RubyWay
With alias_method you can wrapan existing method...
...effectively intercepting any callsand injecting any desired behavior
...effectively intercepting any callsand injecting any desired behavior
Meta-ProgrammingEvents
Ruby has a rich event modelassociated with static and dynamicchanges of the codeIncluded Hook
Method Missing
Ruby provides several hookmethods that can be used to createdcustom behaviorsmethod_missingmethod_addedmethod_removed
Ruby’s Markup Builder is anexample of what can be achievedwith method missing
Let’s implement the greeter exampleusing method_missing
greeter using method_missing
greeter using method_missing
Trellis...or what happens when you have too much timein between consulting gigsand your friends no longer call you
I was bored...In the Ruby world I’ve worked with Rails and Merb...thinking of web apps in terms of request & responsemeanw...
Started to hack to see what it would be to buildsomething like Tapestry/Wicket in Ruby...actually it all started as an lea...
You might beasking yourself,but why?
Why not?
My goals:✓Magic like Rails; less code more action✓ Small like Camping... a micro-framework✓Components like Tapestry/Wicket...
The big picture:Trellis ApplicationPages Componentshashas{declares pages useddeclares a home pagedispatches request to pag...
The simplest Trellis App, one Application and one PageThe CodeThe Template
What did I use to put this thing together...➡A boat load of meta-programming➡Rack ...HTTP the Ruby way➡Radius ...XML tags ...
Let’s do some code spelunking on the Trellis codebase...yes, there are some things that I’m not proud of but......this is ...
Some of the example applications that I’ve puttogether in order of complexity➡hilo➡guest_book➡hangman➡yui➡stateful_counter...
What havewe learned?
There is more to Ruby than Rails!Building a Framework?Give Ruby a try!Build the language up towardsthe problem
Rack: http://rack.rubyforge.orgRadius: http://radius.rubyforge.orgHpricot: http://code.whytheluckystiff.net/hpricotREXML: ...
www.integrallis.com
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
Upcoming SlideShare
Loading in...5
×

Ruby Metaprogramming - OSCON 2008

772

Published on

Learn about the art of writing code that writes code. In this session we will explore some of the metaprogramming techniques that make Ruby the ideal language for framework development.

Metaprogramming techniques can greatly reduce the amount of code you write while clarifying the intend of your code. Learn how frameworks like Ruby on Rails and others exploit metaprogramming to infuse that special magic that only open dynamic languages can produce.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
772
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
8
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Ruby Metaprogramming - OSCON 2008"

  1. 1. Metaprogramingin RubyBrian Sam-Bodden
  2. 2. What’s this all about?‣ We’ll learn...‣ mainly about Ruby’s Meta-programming power‣ about a language doesn’t treat you like a moron‣ what happens when dynamic meets object-oriented‣ why Ruby is superb for building frameworks‣ what happens when meta-programming‣ ...meets someone with too much free-time
  3. 3. Ruby
  4. 4. Ruby Ideals:Programming should be fun!“I believe people want to express themselves when theyprogram.They don’t want to fight with the language.Programming languages must feel natural toprogrammers.”MatzThe language should treat you like a responsible adult!
  5. 5. Ruby
  6. 6. Rubyis...
  7. 7. Rubyis...✓Object-Oriented
  8. 8. Rubyis...✓Object-Oriented✓General Purpose
  9. 9. Rubyis...✓Object-Oriented✓ Interpreted✓General Purpose
  10. 10. Rubyis...✓Object-Oriented✓Dynamic✓ Interpreted✓General Purpose
  11. 11. Rubyis...✓Object-Oriented✓Dynamic✓ Interpreted✓General Purpose✓ Garbage-collected
  12. 12. Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Garbage-collected
  13. 13. Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Multi-paradigm✓ Garbage-collected
  14. 14. Rubyis...✓Object-Oriented✓Reflective ✓Dynamic✓ Interpreted✓General Purpose✓ Multi-paradigm✓ Garbage-collected✓Elegant
  15. 15. Without Ruby there would beno RailsRuby’s meta-programing is the keyfeature that makes Rails magical
  16. 16. OpenClasses
  17. 17. Say we have an Array like:
  18. 18. Say we have an Array like:[1,2,3,4,5]
  19. 19. Say we have an Array like:[1,2,3,4,5]and we want to sum ofall of its elements
  20. 20. Let’s try something like:
  21. 21. Let’s try something like:[1,2,3,4,5].sum
  22. 22. Let’s try something like:[1,2,3,4,5].sum
  23. 23. Let’s try something like:[1,2,3,4,5].sumRats! Doesn’t work in Ruby
  24. 24. Let’s try something like:[1,2,3,4,5].sumRats! Doesn’t work in Ruby… yet!
  25. 25. Ruby classes are
  26. 26. Ruby classes are
  27. 27. Ruby classes areWe can teach the Array class a new behavior
  28. 28. Ruby classes areWe can teach the Array class a new behavior
  29. 29. Let’s try again!
  30. 30. Let’s try again!
  31. 31. Let’s try again!All you need to do is load the filecontaining the enhancements
  32. 32. Code asDataBend at will your code should
  33. 33. When code can be manipulated as dataa whole world of possibilities opensIn Ruby you can evaluate thecontents of a string
  34. 34. Code that invokes code,that invokes code
  35. 35. Code that invokes code,that invokes code
  36. 36. Code that invokes code,that invokes codeThere you go, there you go
  37. 37. Ruby provides the eval family ofmethods for runtime execution ofcode stored in strings
  38. 38. Ruby provides the eval family ofmethods for runtime execution ofcode stored in strings
  39. 39. Ruby provides the eval family ofmethods for runtime execution ofcode stored in stringseval will evaluate any string
  40. 40. instance_eval can evaluate astring or a code block
  41. 41. instance_eval can evaluate astring or a code block
  42. 42. instance_eval can evaluate astring or a code blockin the context of the receiver
  43. 43. class_eval can evaluate a string or a code blockin the context of the class or module it is called on
  44. 44. class_eval can evaluate a string or a code blockin the context of the class or module it is called on
  45. 45. In Ruby we try to think about sending a message toan object rather than calling a method on an object
  46. 46. In Ruby we try to think about sending a message toan object rather than calling a method on an objectIn simple cases (above) syntactic sugar hides it,but we can use it in interesting ways...
  47. 47. Meta-programming
  48. 48. ...is about programs thatwrite programsMeta-programming...it’s a superb tool for buildingframeworks...it’s the key ingredient for buildingdomain-specific languages
  49. 49. Ruby’s is a great vehicle formeta-programming because it is:dynamic and reflexiveopen and malleableclean syntaxcode is data, data is codeprogramming event model
  50. 50. ...uses meta-programming to bringthe language closer to the problem...is a collection of domain-specificlanguages (DSL) for building webapplicationsRuby on Rails
  51. 51. SingletonClass
  52. 52. In Ruby you can enhance aparticular instance of a classRuby uses a proxy class known asthe singleton classMeta-class:The singleton forClass objects
  53. 53. class_eval indirectly uses the meta-classadding a singleton method to the class
  54. 54. Rails relies heavily on Ruby’s abilityto dynamically enhance a class
  55. 55. Rails relies heavily on Ruby’s abilityto dynamically enhance a class
  56. 56. Shortcuts such as define_methodexist to make life easier
  57. 57. Accessing the singleton meta-classexplicitly
  58. 58. Child classes get enhanced withclass methods
  59. 59. Inheritancethe Ruby Way
  60. 60. Many Ruby DSLs create classmethods on subclasses using themeta-class (singleton class)
  61. 61. Rails uses this technique in ActiveRecord
  62. 62. A module with a “Base” class
  63. 63. Methods get added to our classes withsimple declarationsGetting closer to a DSL!
  64. 64. Now our class has a new set of classmethods
  65. 65. Now our class has a new set of classmethods
  66. 66. AOPthe RubyWay
  67. 67. With alias_method you can wrapan existing method...
  68. 68. ...effectively intercepting any callsand injecting any desired behavior
  69. 69. ...effectively intercepting any callsand injecting any desired behavior
  70. 70. Meta-ProgrammingEvents
  71. 71. Ruby has a rich event modelassociated with static and dynamicchanges of the codeIncluded Hook
  72. 72. Method Missing
  73. 73. Ruby provides several hookmethods that can be used to createdcustom behaviorsmethod_missingmethod_addedmethod_removed
  74. 74. Ruby’s Markup Builder is anexample of what can be achievedwith method missing
  75. 75. Let’s implement the greeter exampleusing method_missing
  76. 76. greeter using method_missing
  77. 77. greeter using method_missing
  78. 78. Trellis...or what happens when you have too much timein between consulting gigsand your friends no longer call you
  79. 79. I was bored...In the Ruby world I’ve worked with Rails and Merb...thinking of web apps in terms of request & responsemeanwhile... in the Java world I was working withTapestry and Wicket...thinking about Pages, Components and Events
  80. 80. Started to hack to see what it would be to buildsomething like Tapestry/Wicket in Ruby...actually it all started as an learning exercise...but then I kept going...somehow I ended building component-orientedweb framework in Ruby...part of a conversation among friends about the needfor IoC and AOP frameworks for dynamic languages
  81. 81. You might beasking yourself,but why?
  82. 82. Why not?
  83. 83. My goals:✓Magic like Rails; less code more action✓ Small like Camping... a micro-framework✓Components like Tapestry/Wicket✓Clean HTML templates...✓...but also programatic HTML generation✓Non-managed components, no pooling
  84. 84. The big picture:Trellis ApplicationPages Componentshashas{declares pages useddeclares a home pagedispatches request to pages} {defines a templateprovides event handlerspasses events to thecomponentsprovides reusable logicresponds to eventscan be stateless (tags)or stateful
  85. 85. The simplest Trellis App, one Application and one PageThe CodeThe Template
  86. 86. What did I use to put this thing together...➡A boat load of meta-programming➡Rack ...HTTP the Ruby way➡Radius ...XML tags for the templates➡Builder ...for building HTML/XML➡Hpricot, REXML ...parsing searching HTML/XML➡Paginator ...for duh, pagination➡Parts of Rails ...so far ActiveSupport (Inflectors)
  87. 87. Let’s do some code spelunking on the Trellis codebase...yes, there are some things that I’m not proud of but......this is pre-alpha, unreleased v0.000001;-)
  88. 88. Some of the example applications that I’ve puttogether in order of complexity➡hilo➡guest_book➡hangman➡yui➡stateful_counters➡flickr➡simple_blog➡crud_components
  89. 89. What havewe learned?
  90. 90. There is more to Ruby than Rails!Building a Framework?Give Ruby a try!Build the language up towardsthe problem
  91. 91. Rack: http://rack.rubyforge.orgRadius: http://radius.rubyforge.orgHpricot: http://code.whytheluckystiff.net/hpricotREXML: http://www.germane-software.com/software/rexmlBuilder: http://builder.rubyforge.orgPaginator: http://paginator.rubyforge.orgYUI (Yahoo! UI Library): http://open.yahoo.com/yuiTrellis (Not ReleasedYet)Trellis @ RubyForge: http://rubyforge.org/projects/trellisTrellis Website: http://www.trellisframework.orgResources
  92. 92. www.integrallis.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×