SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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

What's hot (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
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 ...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

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