SlideShare a Scribd company logo
RUBY META
PROGRAMMING.
@fnando
AVISOS.
TUDO É OBJETO.
    INCLUINDO CLASSES.
MUITO CÓDIGO.
VARIÁVEIS DE
    CLASSE.
class MyLib
  @@name = "mylib"

  def self.name
    @@name
  end
end
MyLib.name
#=> “mylib”
class MyOtherLib < MyLib
  @@name = "myotherlib"
end
MyOtherLib.name
#=> “myotherlib”

MyLib.name
#=> “myotherlib”
VARIÁVEIS DE
     CLASSE SÃO
COMPARTILHADAS.
VARIÁVEIS DE
  INSTÂNCIA.
class MyLib
  @name = "mylib"

  def self.name
    @name
  end
end
MyLib.name
#=> “mylib”
class MyOtherLib < MyLib
  @name = "myotherlib"
end
MyOtherLib.name
#=> “myotherlib”

MyLib.name
#=> “mylib”
VARIÁVEIS DE
  INSTÂNCIA
 PERTENCEM
 AO OBJETO.
METACLASSE.
class MyLib
  class << self
  end
end
class MyLib # ruby 1.9.2+
  singleton_class.class_eval do
  end
end
class Object
  def singleton_class
    class << self; self; end
  end
end unless Object.respond_to?(:singleton_class)
class MyLib
  class << self
    attr_accessor :name
  end
end
MyLib.name = "mylib"
MyLib.name
#=> mylib
BLOCOS.
MÉTODOS PODEM
RECEBER BLOCOS.
def run(&block)
end
BLOCOS PODEM
SER EXECUTADOS.
def run(&block)
  yield arg1, arg2
end
def run(&block)
  block.call(arg1, arg2)
end
def run(&block)
  block[arg1, arg2]
end
def run(&block) # ruby   1.9+
  block.(arg1, arg2)
end
METACLASSE,
   BLOCOS E
 VARIÁVEL DE
  INSTÂNCIA.
MyLib.configure do |config|
  config.name = "mylib"
end
class MyLib
  class << self
    attr_accessor :name
  end

  def self.configure(&block)
    yield self
  end
end
EVALUATION.
eval, class_eval, e
    instance_eval
MyLib.class_eval <<-RUBY
  "running inside class"
RUBY
#=> “running inside class”
MyLib.class_eval do
  "running inside class"
end
#=> “running inside class”
handler = proc {
  self.kind_of?(MyLib)
}

handler.call
#=> false
handler = proc {
  self.kind_of?(MyLib)
}

lib.instance_eval(&handler)
#=> true
BLOCOS,
METACLASSE,
VARIÁVEIS DE
  INSTÂNCIA,
 EVALUATION.
MyLib.configure do
  self.name = "mylib"
  name
  #=> “mylib”
end
class MyLib
  class << self
    attr_accessor :name
  end

  def self.configure(&block)
    instance_eval(&block)
  end
end
DEFINIÇÃO DE
   MÉTODOS.
MONKEY
PATCHING.
class Integer
  def kbytes
    self * 1024
  end
end

128.kbytes
#=> 131072
define_method.
MyLib.class_eval do
  define_method "name" do
    @name
  end

  define_method "name=" do |name|
    @name = name
  end
end
lib = MyLib.new
lib.name = "mynewname"
lib.name
#=> “mynewname”
EVALUATION.
MyLib.class_eval <<-RUBY
  def self.name
    "mylib"
  end

  def name
     "mylib's instance"
  end
RUBY
MyLib.class_eval do
  def self.name
    "mylib"
  end

  def name
    "mylib's instance"
  end
end
MyLib.name
#=> “mylib”

MyLib.new.name
#=> “mylib’s instance”
BLOCOS,
 EVALUATION,
DEFINIÇÃO DE
   MÉTODOS.
MyLib.class_eval do
  name "mylib"

  name
  #=> “mylib”
end
class MyLib
  def self.accessor(method)
    class_eval <<-RUBY
      def self.#{method}(*args)
         if args.size.zero?
           @#{method}
         else
           @#{method} = args.last
         end
      end
    RUBY
  end

  accessor :name
end
MyLib.class_eval do
  name "mylib"

  name
  #=> “mylib”
end
configure do
  name "mylib"

  name
  #=> “mylib”
end
def configure(&block)
  MyLib.instance_eval(&block)
end
DISCLAIMER.
METHOD MISSING.
MyLib.new.invalid
NoMethodError: undefined method ‘invalid’ for
#<MyLib:0x10017e2f0>
class MyLib
  NAMES = { :name => "mylib’s instance" }

  def method_missing(method, *args)
    if NAMES.key?(method.to_sym)
      NAMES[method.to_sym]
    else
      super
    end
  end
end
class MyLib
  #...

 def respond_to?(method, include_private = false)
   if NAMES.key?(method.to_sym)
     true
   else
     super
   end
 end
end
lib.name
#=> “mylib’s instance”



lib.respond_to?(:name)
#=> true
MIXINS.
class MyLib
  extend Accessor
  accessor :name
end

class MyOtherLib
  extend Accessor
  accessor :name
end
module Accessor
  def accessor(name)
    class_eval <<-RUBY
      def self.#{name}(*args)
         if args.size.zero?
           @#{name}
         else
           @#{name} = args.last
         end
      end
    RUBY
  end
end
MONKEY
PATCHING, MIXINS,
     EVALUATION,
        DYNAMIC
   DISPATCHING E
          HOOKS.
class Conference < ActiveRecord::Base
  has_permalink
end
"welcome to QConSP".to_permalink
#=> “welcome-to-qconsqp”
class String
  def to_permalink
    self.downcase.gsub(/[^[a-z0-9]-]/, "-")
  end
end
class Conference < ActiveRecord::Base
  before_validation :generate_permalink

  def generate_permalink
    write_attribute :permalink, name.to_s.to_permalink
  end
end
module Permalink
end

ActiveRecord::Base.send :include, Permalink
module Permalink
  def self.included(base)
    base.send :extend, ClassMethods
  end
end
module Permalink
  # ...
  module ClassMethods
    def has_permalink
      class_eval do
        before_validation :generate_permalink
        include InstanceMethods
      end
    end
  end
end
module Permalink
  # ...
 module InstanceMethods
   def generate_permalink
     write_attribute :permalink, name.to_s.to_permalink
   end
 end
end
conf = Conference.create(:name => "QConSP 2010")
conf.permalink
#=> "qconsp-2010"
ENTÃO...
META
PROGRAMMING É
  COMPLICADO.
MAS NEM TANTO.
APRENDA RUBY.
OBRIGADO.
nandovieira.com.br
simplesideias.com.br
       spesa.com.br
  github.com/fnando
            @fnando

More Related Content

What's hot (10)

PPTX
jQuery PPT
Dominic Arrojado
 
PPTX
Jquery fundamentals
Salvatore Fazio
 
PDF
PHP Belfast | Collection Classes
Tim Swann
 
PPT
jQuery
Mohammed Arif
 
PDF
Simplifying Code: Monster to Elegant in 5 Steps
tutec
 
PPTX
jQuery Best Practice
chandrashekher786
 
PPT
Strings
Max Friel
 
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
PDF
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle
 
PDF
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
jQuery PPT
Dominic Arrojado
 
Jquery fundamentals
Salvatore Fazio
 
PHP Belfast | Collection Classes
Tim Swann
 
Simplifying Code: Monster to Elegant in 5 Steps
tutec
 
jQuery Best Practice
chandrashekher786
 
Strings
Max Friel
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle
 
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 

Similar to Ruby Metaprogramming (20)

PDF
Metaprogramming 101
Nando Vieira
 
PPTX
Ruby object model
Chamnap Chhorn
 
KEY
Ruby objects
Reuven Lerner
 
PDF
Metaprogramming in Ruby
Nicolò Calcavecchia
 
PDF
Designing Ruby APIs
Wen-Tien Chang
 
PPTX
Introduction to the Ruby Object Model
Miki Shiran
 
PDF
Metaprogramming
Alex Koppel
 
PDF
Steady with ruby
Christopher Spring
 
PDF
Ruby basics
Aditya Tiwari
 
PPT
Metaprogramming With Ruby
Farooq Ali
 
PPTX
Ruby Metaprogramming
Thaichor Seng
 
KEY
Metaprogramming Primer (Part 1)
Christopher Haupt
 
KEY
Ruby 2.0: to infinity... and beyond!
Fabio Kung
 
PDF
Metaprogramming ruby
GeekNightHyderabad
 
PDF
Story for a Ruby on Rails Single Engineer
TylerJohnson988371
 
PDF
TDC 2015 - Metaprogramação na prática
Guilherme Carreiro
 
KEY
Ruby: Beyond the Basics
Michael Koby
 
KEY
Learn Ruby 2011 - Session 4 - Objects, Oh My!
James Thompson
 
PPTX
Day 1 - Intro to Ruby
Barry Jones
 
PDF
Classboxes, nested methods, and real private methods
Shugo Maeda
 
Metaprogramming 101
Nando Vieira
 
Ruby object model
Chamnap Chhorn
 
Ruby objects
Reuven Lerner
 
Metaprogramming in Ruby
Nicolò Calcavecchia
 
Designing Ruby APIs
Wen-Tien Chang
 
Introduction to the Ruby Object Model
Miki Shiran
 
Metaprogramming
Alex Koppel
 
Steady with ruby
Christopher Spring
 
Ruby basics
Aditya Tiwari
 
Metaprogramming With Ruby
Farooq Ali
 
Ruby Metaprogramming
Thaichor Seng
 
Metaprogramming Primer (Part 1)
Christopher Haupt
 
Ruby 2.0: to infinity... and beyond!
Fabio Kung
 
Metaprogramming ruby
GeekNightHyderabad
 
Story for a Ruby on Rails Single Engineer
TylerJohnson988371
 
TDC 2015 - Metaprogramação na prática
Guilherme Carreiro
 
Ruby: Beyond the Basics
Michael Koby
 
Learn Ruby 2011 - Session 4 - Objects, Oh My!
James Thompson
 
Day 1 - Intro to Ruby
Barry Jones
 
Classboxes, nested methods, and real private methods
Shugo Maeda
 
Ad

More from Nando Vieira (6)

PDF
A explosão do Node.js: JavaScript é o novo preto
Nando Vieira
 
PDF
Presentta: usando Node.js na prática
Nando Vieira
 
PDF
Testando Rails apps com RSpec
Nando Vieira
 
PDF
O que mudou no Ruby 1.9
Nando Vieira
 
PDF
jQuery - Javascript para quem não sabe Javascript
Nando Vieira
 
PDF
Test-driven Development no Rails - Começando com o pé direito
Nando Vieira
 
A explosão do Node.js: JavaScript é o novo preto
Nando Vieira
 
Presentta: usando Node.js na prática
Nando Vieira
 
Testando Rails apps com RSpec
Nando Vieira
 
O que mudou no Ruby 1.9
Nando Vieira
 
jQuery - Javascript para quem não sabe Javascript
Nando Vieira
 
Test-driven Development no Rails - Começando com o pé direito
Nando Vieira
 
Ad

Recently uploaded (20)

PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
July Patch Tuesday
Ivanti
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 

Ruby Metaprogramming