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

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 JasmineRaimonds Simanovskis
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyRaimonds Simanovskis
 
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 frameworkG Woo
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
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 SlickHermann Hueck
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartConanandvns
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
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.5Leonardo Proietti
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
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...go_oh
 

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

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úsenostiJano Suchal
 
Peter Mihalik: Puppet
Peter Mihalik: PuppetPeter Mihalik: Puppet
Peter Mihalik: PuppetJano Suchal
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Bonetics: Mastering Puppet Workshop
Bonetics: Mastering Puppet WorkshopBonetics: Mastering Puppet Workshop
Bonetics: Mastering Puppet WorkshopJano Suchal
 
Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Jano Suchal
 
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?Jano Suchal
 
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-2010Jano Suchal
 

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

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.toster
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
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 DornellesTchelinux
 
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 FrameworkBen Scofield
 
Documenting from the Trenches
Documenting from the TrenchesDocumenting from the Trenches
Documenting from the TrenchesXavier 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 2011camp_drupal_ua
 
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 logicTse-Ching Ho
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
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 RubyFabio Akita
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008maximgrp
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxDr Nic Williams
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 

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

Slovensko.Digital: Čo ďalej?
Slovensko.Digital: Čo ďalej?Slovensko.Digital: Čo ďalej?
Slovensko.Digital: Čo ďalej?Jano Suchal
 
Improving code quality
Improving code qualityImproving code quality
Improving code qualityJano Suchal
 
Beyond search queries
Beyond search queriesBeyond search queries
Beyond search queriesJano Suchal
 
Rank all the things!
Rank all the things!Rank all the things!
Rank all the things!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
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practiceJano 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 monitoringJano Suchal
 
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ázyJano Suchal
 
Profiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applicationsProfiling and monitoring ruby & rails applications
Profiling and monitoring ruby & rails applicationsJano 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.czJano Suchal
 
PostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practicePostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practiceJano Suchal
 
elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practiceJano Suchal
 
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ť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

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.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