SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Name: Thaichor Seng
Position: Junior Developer at Yoolk.Inc

I‟m currently working on creating
Restaurant Menu application
using Ruby on Rails.
•   Sugar Syntax
•   Dynamic Language
•   English Like
•   Lots of built-in methods
•   Metaprogramming
Metaprogramming is writing code that writes code.

Here are some method using for metaprogramming:
• define_method()
• method_missing()
• class_eval()
• eval()
class MyClass
   define_method :my_method do |my_arg|
     my_arg * 3
   end
   # def my_method(my_arg)
   # my_arg * 3
   # end
end

obj = MyClass.new
obj.my_method(2) # => 6
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
   end
end
c = Currency.new(14)
c.to_usd           # 14 usd
c.to_riel          # 14 riel
class Lawyer
end

nick = Lawyer.new
nick.talk_simple
NoMethodError: undefined method „talk_simple' for
#<Lawyer:0x3c848>
class Lawyer
   def method_missing(method, *args)
     puts "You called: #{method}(#{args.join(', ')})"
   end
end
nick = Lawyer.new
nick.talk_simple     # You called talk_simple()
Nick.talk(a, b)      # You called talk(a, b)
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
   end
end
icecream = MyOpenStruct.new
icecream.flavor = "vanilla“       # nil
icecream.flavor                   # vanilla
def add_method_to(a_class)
  a_class.class_eval do
     def m
       'Hello!'
     end
  end
end

add_method_to String
"abc".m       # => "Hello!“
map = { "update" => "deploy:update" ,
         "restart" => "deploy:restart" ,
         "cleanup" => "deploy:cleanup" }
map.each do |old, new|
eval "task(#{old.inspect}) do
warn "[DEPRECATED] `#{old}' is deprecated. Use `#{new}' instead."
find_and_execute_task(#{new.inspect})
end"
end
The End

Weitere ähnliche Inhalte

Was ist angesagt?

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Powershell function
Powershell functionPowershell function
Powershell function
LearningTech
 

Was ist angesagt? (18)

Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所Grailsでドメイン駆動設計を実践する時の勘所
Grailsでドメイン駆動設計を実践する時の勘所
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
RSpec
RSpecRSpec
RSpec
 
Excellent
ExcellentExcellent
Excellent
 
Value objects
Value objectsValue objects
Value objects
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby Exceptions
Ruby ExceptionsRuby Exceptions
Ruby Exceptions
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decorators
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Cucumber testing
Cucumber testingCucumber testing
Cucumber testing
 
WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016
WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016
WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016
 
Simplifying Code: Monster to Elegant in 5 Steps
Simplifying Code: Monster to Elegant in 5 StepsSimplifying Code: Monster to Elegant in 5 Steps
Simplifying Code: Monster to Elegant in 5 Steps
 
Powershell function
Powershell functionPowershell function
Powershell function
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsМихаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commands
 

Ähnlich wie Ruby Metaprogramming

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
ConFoo
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 

Ähnlich wie Ruby Metaprogramming (20)

A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Why ruby
Why rubyWhy ruby
Why ruby
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Ruby
RubyRuby
Ruby
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Dsl
DslDsl
Dsl
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
Intro to ruby
Intro to rubyIntro to ruby
Intro to ruby
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Steady with ruby
Steady with rubySteady with ruby
Steady with ruby
 

Kürzlich hochgeladen

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 

Kürzlich hochgeladen (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

Ruby Metaprogramming

  • 1.
  • 2. Name: Thaichor Seng Position: Junior Developer at Yoolk.Inc I‟m currently working on creating Restaurant Menu application using Ruby on Rails.
  • 3. Sugar Syntax • Dynamic Language • English Like • Lots of built-in methods • Metaprogramming
  • 4. Metaprogramming is writing code that writes code. Here are some method using for metaprogramming: • define_method() • method_missing() • class_eval() • eval()
  • 5. class MyClass define_method :my_method do |my_arg| my_arg * 3 end # def my_method(my_arg) # my_arg * 3 # end end obj = MyClass.new obj.my_method(2) # => 6
  • 6. 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 end end c = Currency.new(14) c.to_usd # 14 usd c.to_riel # 14 riel
  • 7. class Lawyer end nick = Lawyer.new nick.talk_simple NoMethodError: undefined method „talk_simple' for #<Lawyer:0x3c848>
  • 8. class Lawyer def method_missing(method, *args) puts "You called: #{method}(#{args.join(', ')})" end end nick = Lawyer.new nick.talk_simple # You called talk_simple() Nick.talk(a, b) # You called talk(a, b)
  • 9. 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 end end icecream = MyOpenStruct.new icecream.flavor = "vanilla“ # nil icecream.flavor # vanilla
  • 10. def add_method_to(a_class) a_class.class_eval do def m 'Hello!' end end end add_method_to String "abc".m # => "Hello!“
  • 11. map = { "update" => "deploy:update" , "restart" => "deploy:restart" , "cleanup" => "deploy:cleanup" } map.each do |old, new| eval "task(#{old.inspect}) do warn "[DEPRECATED] `#{old}' is deprecated. Use `#{new}' instead." find_and_execute_task(#{new.inspect}) end" end