Basics of Metaprogramming in Ruby

624 views
508 views

Published on

budapest ruby meetup, 10/2013
Tamas Tompa

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

No Downloads
Views
Total views
624
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
19
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Basics of Metaprogramming in Ruby

  1. 1. Basics of Metaprogramming Tamás Tompa (Digital Natives) tamas.tompa@digitalnatives.hu Budapest Ruby Meetup 2013 02/10/2013 Thursday, October 3, 13
  2. 2. “Metaprogramming is writing code that writes code.” Thursday, October 3, 13
  3. 3. what for? § examples § writing a wrapper § DSL (domain specific language) § keep your code DRY § extend core ruby classes Thursday, October 3, 13
  4. 4. runtime § static vs dynamic metaprogramming § everything is object (even classes) § code introspection Thursday, October 3, 13
  5. 5. well known example § ActiveRecord::Base § reads the schema at runtime § discovers fields § conventions Thursday, October 3, 13
  6. 6. monkey patching § monkey patch is a way to extend or modify the run-time code of dynamic languages without altering the original source code § can be dangerous § always carefully check the existing methods Thursday, October 3, 13
  7. 7. basics obj = MyClass.new obj.class # => MyClass "hello".class # => String String.class # => Class obj.instance_variables # => [:@v] obj.methods.grep(/my/) # => [:my_method] Class.instance_methods(false) Thursday, October 3, 13
  8. 8. basics # ignore inherited methods Class.instance_methods(false) String.superclass # => Object Object.superclass # => BasicObject BasicObject.superclass # => nil # module and kernel D.ancestors # => [D, C, M, Object, Kernel, BasicObject] Thursday, October 3, 13
  9. 9. “Classes themselves are nothing but objects.” Thursday, October 3, 13
  10. 10. object model Thursday, October 3, 13
  11. 11. dynamic methods class MyClass define_method :my_method do |my_arg| my_arg * 3 end end obj = MyClass.new obj.my_method(2) # => 6 obj.send(:my_method, 2) # => 6 Thursday, October 3, 13
  12. 12. generating methods class Computer def initialize(computer_id, data_source) end def self.define_component(name) define_method(name) do info = @data_source.send "get_#{name}_info" , @id price = @data_source.send "get_#{name}_price" , @id end end define_component :mouse define_component :cpu end Thursday, October 3, 13
  13. 13. method missing class Lawyer def method_missing(method, *args) puts "You called: #{method}(#{args.join(', ')})" puts "(You also passed it a block)" if block_given? end end bob = Lawyer.new bob.talk_simple('a' , 'b' ) do # a block end You called: talk_simple(a, b) (You also passed it a block) Thursday, October 3, 13
  14. 14. http://pragprog.com/book/ppmetr/metaprogramming-ruby Thursday, October 3, 13
  15. 15. We’re hiring! http://digitalnatives.hu/jobs Thursday, October 3, 13

×