SlideShare a Scribd company logo
1 of 34
Download to read offline
Metaprogramovanie
   #1. Polopravdy o
  objektovom (meta)
        modeli
                  mar
           @ tkra         arla
                  ich alb
             @m
Kód,
ktorý píše kód,
ktorý píše kód,
ktorý píše kód..
class Car
  def engine
    @engine
  end

  def engine=(engine)
    @engine = engine
  end
end
class Car
  attr_accessor :engine,
                :wheels,
                :brakes
end
namespace :db do
  desc "Load database migrations"
  task :migrate do
    # run migrations
  end
end
Presentation
  .find_by_event_and_name
     ("Rubyslava",
      "Metaprogramovanie")
Application.routes.draw do
  resources :events do
    resources :presentations
    get :attend,
        :on => :collection
  end
end
class Presentation < AR::Base
  index do
    name
    description
  end
end
Základné kamene
metaprogramovania
   ●   premakaný objektový model
       ○ dynamic method lookup
       ○ moduly (include, extend)
   ●   open classes
   ●   self a kontexty
   ●   všetko je vykonateľný kód
   ●   callbacky
   ●   pohadzovateľný kód (bloky)
Moduly


●   Namespace
●   Kontajner pre metódy

class Class < Module
module Greeter
  def greet
    puts "Hallo Welt"
  end
end

class Application
  include Greeter
end

Application.new.greet
#=> "Hallo Welt"
Application.greet
#=> Undefined method "greet"
module Greeter
  def greet
    puts "Hallo Welt"
  end
end

class Application
  extend Greeter
end

Application.new.greet
#=> Undefined method "greet"
Application.greet
#=> "Hallo Welt"
class Presentation < AR::Base
  acts_as_searchable
end

Presentation.new
         ("Metaprogramming magic")
presentation.matches?(/magic/)
Presentation.search(/magic/i)
module Searchable
  def acts_as_searchable
    include InstanceMethods
    extend ClassMethods
  end

 module ClassMethods
   def search(pattern)
     all.select { |m| m.description =~ pattern }
   end
 end

  module InstanceMethods
    def matches?(pattern)
      description =~ pattern
    end
  end
end
ActiveRecord::Base.extend Searchable
Open Classes

      class String
       def ends_with? pattern
          ...
       end
      end
Dynamic method
lookup                              Object

                                  + equals?




abacus1 = Abacus.new("2 + 3")
                                 Calculator
abacus2 = Abacus.new("3 - 2")
abacus1.add_stone               + eval_expression
abacus1.equals? abacus2
abacus1.reset

                                    Abacus

                                   + add_stone
doc = Nokogiri::Slop(<<-eohtml)
  <html>
    <body>
       <p>first</p>
       <p>second</p>
    </body>
  </html>
eohtml
assert_equal('second',
              doc.html.body.p[1].text)
module Nokogiri
  module Decorators
    module Slop
      def method_missing name, *args, &block
        list = xpath("/#{name}")
        list.length == 1 ? list.first : list
      end
    end
  end
end
Product.find_by_name_and_description('Rubyslava', 'Meta')

class ActiveRecord::Base
  def method_missing(name, *args, &block)
    if name.to_s =~ /^find_by_(.+)$/
      run_find_by_method($1, *args, &block)
    else
      super
    end
  end

  def run_find_by_method(attrs, *args, &block)
    # args => ['Rubyslava', 'Meta']
    attrs = attrs.split('_and_')
    #=> ['name', 'description']
    attrs_with_args = [attrs, args].transpose
    #=> [['name', 'Rubyslava'], ['description', 'Meta']
    conditions = Hash[attrs_with_args]
    #=> {'name' => 'Rubyslava', 'description' => 'Meta'}
    where(conditions).all
  end
end
class Color
  RGB = { red: '#ff0000',
          blue: '#0000ff', orange: '#bb12ee' }

 def initialize(rgb)
   @rgb = rgb
 end

 def to_s
   @rgb
 end

  def self.const_missing(name)
    rgb = RGB[name.downcase]
    if rgb
      Color.new(rgb)
    else
      super
    end
  end
end

puts Color::Blue
Dynamic method call
def dispatcher(klass, method)
  klass.send method
end


method_names = public_instance_methods(true)

tests = method_names.delete_if do |method_name|
  method_name !~ /^test./
end

tests.each do |test|
 send test
end
Dynamic method definition
module SimpleRouting
  def resources(*names)
    names.each do |resource|
      define_method "#{resource}_path" do
        "localhost/#{resource}"
      end
    end
  end
end

class Application
  extend SimpleRouting

  resources :events, :presenters, :topics

  def test_paths
    puts events_path #=> localhost/events
    puts presenters_path #=> localhost/presenters
    puts topics_path #=> localhost/topics
  end
end
H       ks

●   included
●   extended
●   inherited
●   method_added
●   method_removed
●   method_undefined
●   singleton_method_added
●   ...
class DatabaseTasks
  extend SimpleRake

  desc "Load database migrations"
  def migrate
    puts "Migrating.."
  end

  desc "Rollback last migrations"
  def rollback
    puts "Rolling back"
  end
end

DatabaseTasks.list_tasks
module SimpleRake
  @@methods = {}

  def desc(description)
    @@description = description
  end

  def method_added(name)
    @@methods[name] = @@description
  end

  def list_tasks
    @@methods.each do |method, desc|
      puts "#{method} # #{desc}"
    end
  end
end
DatabaseTasks.list_tasks

migrate    # Load database migrations
rollback   # Rollback last migrations
class Presentation < AR::Base
  include Searchable
end

Presentation.new
         ("Metaprogramming magic")
presentation.matches?(/magic/)
Presentation.search(/magic/i)
module Searchable
  def self.included(base)
    base.extend ClassMethods
  end

  def matches?(pattern)
    description =~ pattern
  end

  module ClassMethods
    def search(pattern)
      all.select do |m|
        m.description =~ pattern
      end
    end
  end
end
http://is.gd/metaprogramovanie
Metaprogramovanie #1

More Related Content

What's hot

Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 

What's hot (20)

Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartCon
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Multilingual drupal 7
Multilingual drupal 7Multilingual drupal 7
Multilingual drupal 7
 

Viewers also liked (7)

Vojtech Rinik: Internship v USA - moje skúsenosti
Vojtech Rinik: Internship v USA - moje skúsenostiVojtech Rinik: Internship v USA - moje skúsenosti
Vojtech Rinik: Internship v USA - moje skúsenosti
 
Peter Mihalik: Puppet
Peter Mihalik: PuppetPeter Mihalik: Puppet
Peter Mihalik: Puppet
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Bonetics: Mastering Puppet Workshop
Bonetics: Mastering Puppet WorkshopBonetics: Mastering Puppet Workshop
Bonetics: Mastering Puppet Workshop
 
Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3
 
Ako si vybrať programovácí jazyk alebo framework?
Ako si vybrať programovácí jazyk alebo framework?Ako si vybrať programovácí jazyk alebo framework?
Ako si vybrať programovácí jazyk alebo framework?
 
sme.sk čočítať ontožíur-2010
sme.sk čočítať ontožíur-2010sme.sk čočítať ontožíur-2010
sme.sk čočítať ontožíur-2010
 

Similar to Metaprogramovanie #1

Documenting from the Trenches
Documenting from the TrenchesDocumenting from the Trenches
Documenting from the Trenches
Xavier Noria
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 

Similar to Metaprogramovanie #1 (20)

Dsl
DslDsl
Dsl
 
Why ruby
Why rubyWhy ruby
Why ruby
 
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 Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
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
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Documenting from the Trenches
Documenting from the TrenchesDocumenting from the Trenches
Documenting from the Trenches
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
model.search: customize your own search logic
model.search: customize your own search logicmodel.search: customize your own search logic
model.search: customize your own search logic
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
DataMapper
DataMapperDataMapper
DataMapper
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
TDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em RubyTDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em Ruby
 
Elegant APIs
Elegant APIsElegant APIs
Elegant APIs
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 

More from Jano Suchal

Rank all the (geo) things!
Rank all the (geo) things!Rank all the (geo) things!
Rank all the (geo) things!
Jano Suchal
 
Ako si vybrať programovací jazyk a framework?
Ako si vybrať programovací jazyk a framework?Ako si vybrať programovací jazyk a framework?
Ako si vybrať programovací jazyk a framework?
Jano Suchal
 
Garelic: Google Analytics as App Performance monitoring
Garelic: Google Analytics as App Performance monitoringGarelic: Google Analytics as App Performance monitoring
Garelic: Google Analytics as App Performance monitoring
Jano Suchal
 
Profiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applicationsProfiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applications
Jano Suchal
 
Aký programovací jazyk a framework si vybrať a prečo?
Aký programovací jazyk a framework si vybrať a prečo?Aký programovací jazyk a framework si vybrať a prečo?
Aký programovací jazyk a framework si vybrať a prečo?
Jano Suchal
 
Petr Joachim: Redis na Super.cz
Petr Joachim: Redis na Super.czPetr Joachim: Redis na Super.cz
Petr Joachim: Redis na Super.cz
Jano Suchal
 

More from Jano Suchal (17)

Slovensko.Digital: Čo ďalej?
Slovensko.Digital: Čo ďalej?Slovensko.Digital: Čo ďalej?
Slovensko.Digital: Čo ďalej?
 
Datanest 3.0
Datanest 3.0Datanest 3.0
Datanest 3.0
 
Improving code quality
Improving code qualityImproving code quality
Improving code quality
 
Beyond search queries
Beyond search queriesBeyond search queries
Beyond search queries
 
Rank all the things!
Rank all the things!Rank all the things!
Rank all the things!
 
Rank all the (geo) things!
Rank all the (geo) things!Rank all the (geo) things!
Rank all the (geo) things!
 
Ako si vybrať programovací jazyk a framework?
Ako si vybrať programovací jazyk a framework?Ako si vybrať programovací jazyk a framework?
Ako si vybrať programovací jazyk a framework?
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practice
 
Garelic: Google Analytics as App Performance monitoring
Garelic: Google Analytics as App Performance monitoringGarelic: Google Analytics as App Performance monitoring
Garelic: Google Analytics as App Performance monitoring
 
Miroslav Šimulčík: Temporálne databázy
Miroslav Šimulčík: Temporálne databázyMiroslav Šimulčík: Temporálne databázy
Miroslav Šimulčík: Temporálne databázy
 
Profiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applicationsProfiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applications
 
Aký programovací jazyk a framework si vybrať a prečo?
Aký programovací jazyk a framework si vybrať a prečo?Aký programovací jazyk a framework si vybrať a prečo?
Aký programovací jazyk a framework si vybrať a prečo?
 
Čo po GAMČI?
Čo po GAMČI?Čo po GAMČI?
Čo po GAMČI?
 
Petr Joachim: Redis na Super.cz
Petr Joachim: Redis na Super.czPetr Joachim: Redis na Super.cz
Petr Joachim: Redis na Super.cz
 
PostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practicePostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practice
 
elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practice
 
Odporúčacie systémy a služba sme.sk čo čítať
Odporúčacie systémy a služba sme.sk čo čítaťOdporúčacie systémy a služba sme.sk čo čítať
Odporúčacie systémy a služba sme.sk čo čítať
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

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
 
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...
 
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...
 
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, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
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 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

Metaprogramovanie #1

  • 1. Metaprogramovanie #1. Polopravdy o objektovom (meta) modeli mar @ tkra arla ich alb @m
  • 2. Kód, ktorý píše kód, ktorý píše kód, ktorý píše kód..
  • 3. class Car def engine @engine end def engine=(engine) @engine = engine end end
  • 4.
  • 5. class Car attr_accessor :engine, :wheels, :brakes end
  • 6. namespace :db do desc "Load database migrations" task :migrate do # run migrations end end
  • 7. Presentation .find_by_event_and_name ("Rubyslava", "Metaprogramovanie")
  • 8. Application.routes.draw do resources :events do resources :presentations get :attend, :on => :collection end end
  • 9. class Presentation < AR::Base index do name description end end
  • 10. Základné kamene metaprogramovania ● premakaný objektový model ○ dynamic method lookup ○ moduly (include, extend) ● open classes ● self a kontexty ● všetko je vykonateľný kód ● callbacky ● pohadzovateľný kód (bloky)
  • 11.
  • 12.
  • 13. Moduly ● Namespace ● Kontajner pre metódy class Class < Module
  • 14. module Greeter def greet puts "Hallo Welt" end end class Application include Greeter end Application.new.greet #=> "Hallo Welt" Application.greet #=> Undefined method "greet"
  • 15. module Greeter def greet puts "Hallo Welt" end end class Application extend Greeter end Application.new.greet #=> Undefined method "greet" Application.greet #=> "Hallo Welt"
  • 16. class Presentation < AR::Base acts_as_searchable end Presentation.new ("Metaprogramming magic") presentation.matches?(/magic/) Presentation.search(/magic/i)
  • 17. module Searchable def acts_as_searchable include InstanceMethods extend ClassMethods end module ClassMethods def search(pattern) all.select { |m| m.description =~ pattern } end end module InstanceMethods def matches?(pattern) description =~ pattern end end end ActiveRecord::Base.extend Searchable
  • 18. Open Classes class String def ends_with? pattern ... end end
  • 19. Dynamic method lookup Object + equals? abacus1 = Abacus.new("2 + 3") Calculator abacus2 = Abacus.new("3 - 2") abacus1.add_stone + eval_expression abacus1.equals? abacus2 abacus1.reset Abacus + add_stone
  • 20. doc = Nokogiri::Slop(<<-eohtml) <html> <body> <p>first</p> <p>second</p> </body> </html> eohtml assert_equal('second', doc.html.body.p[1].text)
  • 21. module Nokogiri module Decorators module Slop def method_missing name, *args, &block list = xpath("/#{name}") list.length == 1 ? list.first : list end end end end
  • 22. Product.find_by_name_and_description('Rubyslava', 'Meta') class ActiveRecord::Base def method_missing(name, *args, &block) if name.to_s =~ /^find_by_(.+)$/ run_find_by_method($1, *args, &block) else super end end def run_find_by_method(attrs, *args, &block) # args => ['Rubyslava', 'Meta'] attrs = attrs.split('_and_') #=> ['name', 'description'] attrs_with_args = [attrs, args].transpose #=> [['name', 'Rubyslava'], ['description', 'Meta'] conditions = Hash[attrs_with_args] #=> {'name' => 'Rubyslava', 'description' => 'Meta'} where(conditions).all end end
  • 23. class Color RGB = { red: '#ff0000', blue: '#0000ff', orange: '#bb12ee' } def initialize(rgb) @rgb = rgb end def to_s @rgb end def self.const_missing(name) rgb = RGB[name.downcase] if rgb Color.new(rgb) else super end end end puts Color::Blue
  • 24. Dynamic method call def dispatcher(klass, method) klass.send method end method_names = public_instance_methods(true) tests = method_names.delete_if do |method_name| method_name !~ /^test./ end tests.each do |test| send test end
  • 26. module SimpleRouting def resources(*names) names.each do |resource| define_method "#{resource}_path" do "localhost/#{resource}" end end end end class Application extend SimpleRouting resources :events, :presenters, :topics def test_paths puts events_path #=> localhost/events puts presenters_path #=> localhost/presenters puts topics_path #=> localhost/topics end end
  • 27. H ks ● included ● extended ● inherited ● method_added ● method_removed ● method_undefined ● singleton_method_added ● ...
  • 28. class DatabaseTasks extend SimpleRake desc "Load database migrations" def migrate puts "Migrating.." end desc "Rollback last migrations" def rollback puts "Rolling back" end end DatabaseTasks.list_tasks
  • 29. module SimpleRake @@methods = {} def desc(description) @@description = description end def method_added(name) @@methods[name] = @@description end def list_tasks @@methods.each do |method, desc| puts "#{method} # #{desc}" end end end
  • 30. DatabaseTasks.list_tasks migrate # Load database migrations rollback # Rollback last migrations
  • 31. class Presentation < AR::Base include Searchable end Presentation.new ("Metaprogramming magic") presentation.matches?(/magic/) Presentation.search(/magic/i)
  • 32. module Searchable def self.included(base) base.extend ClassMethods end def matches?(pattern) description =~ pattern end module ClassMethods def search(pattern) all.select do |m| m.description =~ pattern end end end end