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

PDF
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
PPTX
A Blink Into The Rails Magic
PDF
Demystifying Object-Oriented Programming - Midwest PHP
PDF
Demystifying Object-Oriented Programming - Lone Star PHP
PDF
GDI Seattle - Intro to JavaScript Class 1
PDF
Demystifying oop
PDF
CoffeeScript
PPTX
Javascript for the c# developer
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
A Blink Into The Rails Magic
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Lone Star PHP
GDI Seattle - Intro to JavaScript Class 1
Demystifying oop
CoffeeScript
Javascript for the c# developer

What's hot (10)

PPTX
jQuery PPT
PPTX
Jquery fundamentals
PDF
PHP Belfast | Collection Classes
PPT
PDF
Simplifying Code: Monster to Elegant in 5 Steps
PPTX
jQuery Best Practice
PPT
Strings
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
PDF
Wordcamp Fayetteville Pods Presentation (PDF)
PDF
Aplicacoes dinamicas Rails com Backbone
jQuery PPT
Jquery fundamentals
PHP Belfast | Collection Classes
Simplifying Code: Monster to Elegant in 5 Steps
jQuery Best Practice
Strings
jQuery - 10 Time-Savers You (Maybe) Don't Know
Wordcamp Fayetteville Pods Presentation (PDF)
Aplicacoes dinamicas Rails com Backbone
Ad

Similar to Ruby Metaprogramming (20)

PDF
Metaprogramming in Ruby
KEY
Metaprogramming
PDF
Metaprogramming 101
PDF
The Dark Art of Rails Plugins (2008)
KEY
Ruby/Rails
KEY
Ruby: Beyond the Basics
PDF
Extending Rails with Plugins (2007)
KEY
Desarrollando aplicaciones web en minutos
PPTX
Lightning talk
PDF
Metaprogramovanie #1
PDF
Ruby tricks2
KEY
Module Magic
KEY
Dsl
PPTX
Ruby Metaprogramming
KEY
PDF
Ruby — An introduction
KEY
Introducing Ruby
KEY
A tour on ruby and friends
PPTX
Introduction to the Ruby Object Model
KEY
Why ruby
Metaprogramming in Ruby
Metaprogramming
Metaprogramming 101
The Dark Art of Rails Plugins (2008)
Ruby/Rails
Ruby: Beyond the Basics
Extending Rails with Plugins (2007)
Desarrollando aplicaciones web en minutos
Lightning talk
Metaprogramovanie #1
Ruby tricks2
Module Magic
Dsl
Ruby Metaprogramming
Ruby — An introduction
Introducing Ruby
A tour on ruby and friends
Introduction to the Ruby Object Model
Why ruby
Ad

More from Nando Vieira (6)

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

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
KodekX | Application Modernization Development
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Machine learning based COVID-19 study performance prediction
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
The Rise and Fall of 3GPP – Time for a Sabbatical?
Digital-Transformation-Roadmap-for-Companies.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation theory and applications.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Understanding_Digital_Forensics_Presentation.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KodekX | Application Modernization Development
“AI and Expert System Decision Support & Business Intelligence Systems”
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Ruby Metaprogramming