Ruby Metaprogramming

1,482 views

Published on

A short description of how useful ruby metaprogramming.

Published in: Education
  • Be the first to comment

Ruby Metaprogramming

  1. 1. Name: Thaichor SengPosition: Junior Developer at Yoolk.IncI‟m currently working on creatingRestaurant Menu applicationusing Ruby on Rails.
  2. 2. • Sugar Syntax• Dynamic Language• English Like• Lots of built-in methods• Metaprogramming
  3. 3. Metaprogramming is writing code that writes code.Here are some method using for metaprogramming:• define_method()• method_missing()• class_eval()• eval()
  4. 4. class MyClass define_method :my_method do |my_arg| my_arg * 3 end # def my_method(my_arg) # my_arg * 3 # endendobj = MyClass.newobj.my_method(2) # => 6
  5. 5. class Currency def initialize(value) @value = value end [:usd, :riel, :yen, :bat].each do |method| define_method “to_#{method}” do “#{@value.to_s} #{method.to_s}” end endendc = Currency.new(14)c.to_usd # 14 usdc.to_riel # 14 riel
  6. 6. class Lawyerendnick = Lawyer.newnick.talk_simpleNoMethodError: undefined method „talk_simple for#<Lawyer:0x3c848>
  7. 7. class Lawyer def method_missing(method, *args) puts "You called: #{method}(#{args.join(, )})" endendnick = Lawyer.newnick.talk_simple # You called talk_simple()Nick.talk(a, b) # You called talk(a, b)
  8. 8. class MyOpenStruct def initialize @attributes = {} end def method_missing(name, *args) attribute = name.to_s if attribute =~ /=$/ @attributes[attribute.chop] = args[0] else @attributes[attribute] end endendicecream = MyOpenStruct.newicecream.flavor = "vanilla“ # nilicecream.flavor # vanilla
  9. 9. def add_method_to(a_class) a_class.class_eval do def m Hello! end endendadd_method_to String"abc".m # => "Hello!“
  10. 10. map = { "update" => "deploy:update" , "restart" => "deploy:restart" , "cleanup" => "deploy:cleanup" }map.each do |old, new|eval "task(#{old.inspect}) dowarn "[DEPRECATED] `#{old} is deprecated. Use `#{new} instead."find_and_execute_task(#{new.inspect})end"end
  11. 11. The End

×