SlideShare uma empresa Scribd logo
1 de 85
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

PHP Belfast | Collection Classes
PHP Belfast |  Collection ClassesPHP Belfast |  Collection Classes
PHP Belfast | Collection Classes
Tim Swann
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
Wordcamp Fayetteville Pods Presentation (PDF)
Wordcamp Fayetteville Pods Presentation (PDF)Wordcamp Fayetteville Pods Presentation (PDF)
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle
 

Mais procurados (10)

jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
PHP Belfast | Collection Classes
PHP Belfast |  Collection ClassesPHP Belfast |  Collection Classes
PHP Belfast | Collection Classes
 
jQuery
jQueryjQuery
jQuery
 
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
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
Strings
StringsStrings
Strings
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
Wordcamp Fayetteville Pods Presentation (PDF)
Wordcamp Fayetteville Pods Presentation (PDF)Wordcamp Fayetteville Pods Presentation (PDF)
Wordcamp Fayetteville Pods Presentation (PDF)
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 

Semelhante a Ruby Metaprogramming

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
ConFoo
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 

Semelhante a Ruby Metaprogramming (20)

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Lightning talk
Lightning talkLightning talk
Lightning talk
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Module Magic
Module MagicModule Magic
Module Magic
 
Dsl
DslDsl
Dsl
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Ruby
RubyRuby
Ruby
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Introduction to the Ruby Object Model
Introduction to the Ruby Object ModelIntroduction to the Ruby Object Model
Introduction to the Ruby Object Model
 
Why ruby
Why rubyWhy ruby
Why ruby
 

Mais de Nando Vieira (6)

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

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Ruby Metaprogramming