SlideShare a Scribd company logo
Dr Nic
 drnicwilliams.com



DIY Syntax
$ irb
>> $KCODE = quot;uquot;
>> quot;303274quot;
=> quot;üquot;
Isn’t this nicer?

    >> U00FC
    => quot;üquot;
$ sudo gem install charesc
$ irb
>> $KCODE = quot;uquot;
>> require 'rubygems'
>> require 'charesc'
>> quot;charesc is made by Martin D#{U00FC}rstquot;
=> quot;charesc is made by Martin Dürstquot;
>> U00FC
=> quot;üquot;
>> quot;303274quot;
=> quot;üquot;



         charesc
Active
                Records
SELECT * FROM conferences WHERE (start_date > '2007-06-07')

# But, much nicer is...
Active
                Records
SELECT * FROM conferences WHERE (start_date > '2007-06-07')

# But, much nicer is...

Conference.find(:all,
          :conditions => [‘start_date > ?’,Date.today])
Active Records
SELECT conferences.quot;idquot; AS t0_r0,
      conferences.quot;namequot; AS t0_r2, ...,
      conference_sessions.quot;idquot; AS t1_r0,
      conference_sessions.quot;conference_idquot; AS t1_r1, ...
FROM conferences
LEFT OUTER JOIN conference_sessions
ON conference_sessions.conference_id = conferences.id
WHERE (start_date < '2007-05-26')

# But, definitely easier and nicer is...
Active Records
SELECT conferences.quot;idquot; AS t0_r0,
      conferences.quot;namequot; AS t0_r2, ...,
      conference_sessions.quot;idquot; AS t1_r0,
      conference_sessions.quot;conference_idquot; AS t1_r1, ...
FROM conferences
LEFT OUTER JOIN conference_sessions
ON conference_sessions.conference_id = conferences.id
WHERE (start_date < '2007-05-26')

# But, definitely easier and nicer is...

Conference.find(:all,
         :conditions => ['start_date < ?', Date.today],
         :include => :conference_sessions)
Sexy
                     Syntax
ActiveRecords
- no SQL

 ... + marshalling
to objects
Sexy
   Syntax


Convenient
  Code
Schemas
create_table :conferences do |t|
  t.fkey    :user
  t.string :name, :limit => 50
  t.text    :description
  t.date    :start_date, :end_date
  t.auto_dates
end

# instead of...

                                     I can never
                                     remember
                                     SQL syntax
Schemas
create_table :conferences do |t|
  t.fkey    :user
  t.string :name, :limit => 50
  t.text    :description
  t.date    :start_date, :end_date
  t.auto_dates
end

# instead of...



Look up SQL on
                                     I can never
                                     remember
                                     SQL syntax
Composite
         Primary Keys
ProductHistory.find(:first, :conditions =>
['id = ? and start_date = ?', 56, Date.new(2000,5,5)])

# rather...

                                                What about
                                                Ruby syntax
                                                improving on
                                                other Ruby
                                                syntax?
Composite
          Primary Keys
ProductHistory.find(:first, :conditions =>
['id = ? and start_date = ?', 56, Date.new(2000,5,5)])

# rather...

ProductHistory.find(56, Date.new(2000,5,5))
                                                What about
                                                Ruby syntax
class ProductHistory < ActiveRecord::Base       improving on
                                                other Ruby
  set_primary_keys :id, :start_date             syntax?
end
What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does




@user.conference_sessions_for(@conference)
What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does




@user.conference_sessions_for(@conference)
# Returns all ConferenceSessions
# for a user at a conference
What’s this do? #2

@conference_attendees.map_id_and_login_and_full_name
What’s this do? #2

@conference_attendees.map_id_and_login_and_full_name

# map {|att| [att.id, att.login, att.full_name]}
What’s this do? #3
         User.find(params[:id])
What’s this do? #3
@to_user =   @target_db::User.find(params[:id])
                         User.find(params[:id])
What’s this do? #3
@to_user =    @target_db::User.find(params[:id])
                          User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
What’s this do? #3
@to_user =    @target_db::User.find(params[:id])
                          User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
# Copies a User from one database to another

# see Magic Multi-Connection
# http://magicmodels.rubyforge.org
Let’s see how they
       work...
What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does




@user.conference_sessions_for(@conference)
What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does




@user.conference_sessions_for(@conference)
# Returns all ConferenceSessions
# for a user at a conference
What’s this do? #1
class User < ActiveRecord::Base
  has_many :conference_sessions

  def conference_sessions_for(conference)
    conference_sessions.find(:all,
      :conditions => ['conference_id = ?', conference])
  end
end

            No meta-magic, but it gives nice syntax
What’s this do? #2

@attendees.map_by_id_and_login_and_full_name

# map {|att| [att.id, att.login, att.full_name]}
Cute ways to use #map
@users = User.find(:all)
@users.map {|user| user.login}
# => ['drnic', 'topfunky', 'dhh']
Cute ways to use #map
@users = User.find(:all)
@users.map {|user| user.login}
# => ['drnic', 'topfunky', 'dhh']

@users.map &:login
# => ['drnic', 'topfunky', 'dhh']
Cute ways to use #map
@users = User.find(:all)
@users.map {|user| user.login}
# => ['drnic', 'topfunky', 'dhh']

@users.map &:login
# => ['drnic', 'topfunky', 'dhh']

# but it gets ugly when you chain them...

@users.map(&:login).map(&:size)
# => [5, 8, 3]
Cute ways to use #map

# So, instead of...
@users.map(&:login).map(&:size)

# We might like...
@users.map_login.map_size
Remember find_by_xxx ?

def method_missing(method_id, *arguments)
  pattern = /^find_(all_by|by)_([_a-zA-Z]w*)$/
  if match = pattern.match(method_id.to_s)
    finder = determine_finder(match)

# from active_record/base.rb, line 1190
Dissecting the request
def method_missing(method, *args, &block)
  pattern = /(map|select|...)_by_([w_]+??)/
  if (match = method.match(pattern))
    iterator, callmethod = match[1], match[2]

# changed ‘find’ to ‘map’
# or select, reject, each, collect...
Iterating the request

# continued...
iterator, callmethod = match[1], match[2]
self.send(iterator) {|obj| obj.send callmethod }

# @array.map_by_foo
# callmethod => ‘foo’
# #foo invoked on each element of Array
Iterating many callmethods
# continued...
iterator, callmethod = match[1], match[2]
callmethods = callmethod.split('_and_')
callmethods.map do |callmethod|
  self.send(iterator) {|obj| obj.send callmethod }
end

# @array.map_by_foo_and_bar
# callmethods => [‘foo’, ‘bar’]
# #foo and #bar invoked on each element of Array
map_by_method gem
# for complete source:

$ gem install map_by_method
$ mate $RUBYGEMS_PATH/map_by_method-0.6.0/lib/map_by_method.rb
map_by_method gem
# for complete source:

$ gem install map_by_method
$ mate $RUBYGEMS_PATH/map_by_method-0.6.0/lib/map_by_method.rb


# add the following to your ~/.irbrc
require 'map_by_method'
What’s this do? #3
         User.find(params[:id])
What’s this do? #3
@to_user =   @target_db::User.find(params[:id])
                         User.find(params[:id])
What’s this do? #3
@to_user =    @target_db::User.find(params[:id])
                          User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
What’s this do? #3
@to_user =    @target_db::User.find(params[:id])
                          User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
# Copies a User from one database to another

# see Magic Multi-Connection
# http://magicmodels.rubyforge.org
Magic
Multi-Connections
 @db::User.find(params[:id])
MMC - alternate ideas
@db::User.find(params[:id])

# but I would have preferred...

User.find(params[:id]).from_db(@db)
MMC - alternate ideas
@db::User.find(params[:id])

# but I would have preferred...

User.find(params[:id]).from_db(@db)

# but we’d need FindProxies
# like AssociationProxies
But what does this mean?


        @db::User
class creator helper
class Module
  def create_class(class_name, superclass = Object, &block)
    klass = Class.new superclass, &block
    self.const_set class_name, klass
  end
end

>> module Connection; end
>> Connection.create_class 'User'
=> Connection::User
class creator helper
class Module
  def create_class(class_name, superclass = Object, &block)
    klass = Class.new superclass, &block
    self.const_set class_name, klass
  end
end

>> module Connection; end
>> Connection.create_class 'User'
=> Connection::User


                                @db::User
But...the class...
“when to create it?”

When you ask for it!
const_missing
class Module
  alias :old_const_missing :const_missing

  def const_missing(const_id)
    return old_const_missing(const_id) rescue nil
    target_class = quot;::#{const_id}quot;.constantize rescue nil
    raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class
    create_class(const_id, target_class)
  end
end
const_missing
class Module
  alias :old_const_missing :const_missing

  def const_missing(const_id)
    return old_const_missing(const_id) rescue nil
    target_class = quot;::#{const_id}quot;.constantize rescue nil
    raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class
    create_class(const_id, target_class)
  end
end


                             magic multi-connections
Picks up root classes
class Person; end

module Remote
  establish_connection :other
end

>> Remote::Person.superclass
=> Person
const_missing
class Module
  def const_missing(const_id)
    return old_const_missing(class_id) rescue nil
    table_name = DrNicMagicModels::Schema.models[const_id]
    raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name
    create_class(class_id, ActiveRecord::Base) do
      set_table_name table_name
    end
  end
end


  “Does the class name match to a table name?”
const_missing
class Module
  def const_missing(const_id)
    return old_const_missing(class_id) rescue nil
    table_name = DrNicMagicModels::Schema.models[const_id]
    raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name
    create_class(class_id, ActiveRecord::Base) do
      set_table_name table_name
    end
  end
                                 dr nic’s magic models
end


  “Does the class name match to a table name?”
const_missing

   >> U00FC
   => quot;üquot;
const_missing
def const_missing(const)
  if const.to_s =~ /^((U(             [0-9ABCEF][0-9A-F]{3}   # general BMP
                            |         D[0-7][0-9A-F]{2}       # excluding surrogates
                            | [1-9A-F][0-9A-F]{4}             # planes 1-15
                            | 10      [0-9A-F]{4}             # plane 16
                          )
                       )*
                     )
                    $/ix
    unescaped = $1.split(/[Uu]/)[1..-1].collect do |hex|      hex.to_i(16) end.pack('U*')
Sexy
  Syntax
Convenient
  Code
Enjoy    En    !

drnicwilliams.com
    by Dr Nic

More Related Content

What's hot

And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
Codemotion
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
Simon Su
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Kacper Gunia
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
Luca Mearelli
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With PythonLuca Mearelli
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
Luca Mearelli
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]
Devon Bernard
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
Yehor Nazarkin
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
Gabriele Lana
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
Bryan Helmig
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
Leon van der Grient
 
Fatc
FatcFatc
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
Michael Pirnat
 
Rapid web development, the right way.
Rapid web development, the right way.Rapid web development, the right way.
Rapid web development, the right way.
nubela
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
Fernando Hamasaki de Amorim
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden
 

What's hot (20)

And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
Scala active record
Scala active recordScala active record
Scala active record
 
Fatc
FatcFatc
Fatc
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Rapid web development, the right way.
Rapid web development, the right way.Rapid web development, the right way.
Rapid web development, the right way.
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 

Viewers also liked

Rubygem Dev And Workflow
Rubygem Dev And WorkflowRubygem Dev And Workflow
Rubygem Dev And WorkflowDr Nic Williams
 
Internetsafety
InternetsafetyInternetsafety
Internetsafety
Wells Ogunquit CSD
 
Living With 1000 Open Source Projects
Living With 1000 Open Source ProjectsLiving With 1000 Open Source Projects
Living With 1000 Open Source Projects
Dr Nic Williams
 
RailsConf Keynote - History of Ruby
RailsConf Keynote - History of RubyRailsConf Keynote - History of Ruby
RailsConf Keynote - History of RubyDr Nic Williams
 
What is your job at your ruby club?
What is your job at your ruby club?What is your job at your ruby club?
What is your job at your ruby club?
Dr Nic Williams
 
What is a kid to do?
What is a kid to do?What is a kid to do?
What is a kid to do?
Wells Ogunquit CSD
 

Viewers also liked (7)

Rubygem Dev And Workflow
Rubygem Dev And WorkflowRubygem Dev And Workflow
Rubygem Dev And Workflow
 
School Class Photos
School Class PhotosSchool Class Photos
School Class Photos
 
Internetsafety
InternetsafetyInternetsafety
Internetsafety
 
Living With 1000 Open Source Projects
Living With 1000 Open Source ProjectsLiving With 1000 Open Source Projects
Living With 1000 Open Source Projects
 
RailsConf Keynote - History of Ruby
RailsConf Keynote - History of RubyRailsConf Keynote - History of Ruby
RailsConf Keynote - History of Ruby
 
What is your job at your ruby club?
What is your job at your ruby club?What is your job at your ruby club?
What is your job at your ruby club?
 
What is a kid to do?
What is a kid to do?What is a kid to do?
What is a kid to do?
 

Similar to RubyEnRails2007 - Dr Nic Williams - DIY Syntax

Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
lachie
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Quality code by design
Quality code by designQuality code by design
Quality code by design
WP Developers Club
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
Wesley Beary
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
Elegant APIs
Elegant APIsElegant APIs
Elegant APIs
Andrew Timberlake
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Mark
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
Eleanor McHugh
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Wesley Beary
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
Jens-Christian Fischer
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
Rabble .
 
Why ruby
Why rubyWhy ruby
Why ruby
rstankov
 
Dsl
DslDsl
Dsl
phoet
 

Similar to RubyEnRails2007 - Dr Nic Williams - DIY Syntax (20)

Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Quality code by design
Quality code by designQuality code by design
Quality code by design
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Elegant APIs
Elegant APIsElegant APIs
Elegant APIs
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
 
Little Big Ruby
Little Big RubyLittle Big Ruby
Little Big Ruby
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
DataMapper
DataMapperDataMapper
DataMapper
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Dsl
DslDsl
Dsl
 

Recently uploaded

Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Holger Mueller
 
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
Boris Ziegler
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
Adam Smith
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
fisherameliaisabella
 
An introduction to the cryptocurrency investment platform Binance Savings.
An introduction to the cryptocurrency investment platform Binance Savings.An introduction to the cryptocurrency investment platform Binance Savings.
An introduction to the cryptocurrency investment platform Binance Savings.
Any kyc Account
 
Mastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnapMastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnap
Norma Mushkat Gaffin
 
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
agatadrynko
 
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
bosssp10
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
Corey Perlman, Social Media Speaker and Consultant
 
amptalk_RecruitingDeck_english_2024.06.05
amptalk_RecruitingDeck_english_2024.06.05amptalk_RecruitingDeck_english_2024.06.05
amptalk_RecruitingDeck_english_2024.06.05
marketing317746
 
Training my puppy and implementation in this story
Training my puppy and implementation in this storyTraining my puppy and implementation in this story
Training my puppy and implementation in this story
WilliamRodrigues148
 
Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431
ecamare2
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
Top Forex Brokers Review
 
Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...
dylandmeas
 
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
AnnySerafinaLove
 
Examining the Effect of Customer Services Quality and Online Reviews in Unive...
Examining the Effect of Customer Services Quality and Online Reviews in Unive...Examining the Effect of Customer Services Quality and Online Reviews in Unive...
Examining the Effect of Customer Services Quality and Online Reviews in Unive...
Adam Smith
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
FelixPerez547899
 
Creative Web Design Company in Singapore
Creative Web Design Company in SingaporeCreative Web Design Company in Singapore
Creative Web Design Company in Singapore
techboxsqauremedia
 
The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...
balatucanapplelovely
 
BeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdfBeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdf
DerekIwanaka1
 

Recently uploaded (20)

Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
 
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
Agency Managed Advisory Board As a Solution To Career Path Defining Business ...
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
 
An introduction to the cryptocurrency investment platform Binance Savings.
An introduction to the cryptocurrency investment platform Binance Savings.An introduction to the cryptocurrency investment platform Binance Savings.
An introduction to the cryptocurrency investment platform Binance Savings.
 
Mastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnapMastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnap
 
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
 
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
 
amptalk_RecruitingDeck_english_2024.06.05
amptalk_RecruitingDeck_english_2024.06.05amptalk_RecruitingDeck_english_2024.06.05
amptalk_RecruitingDeck_english_2024.06.05
 
Training my puppy and implementation in this story
Training my puppy and implementation in this storyTraining my puppy and implementation in this story
Training my puppy and implementation in this story
 
Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
 
Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...
 
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
 
Examining the Effect of Customer Services Quality and Online Reviews in Unive...
Examining the Effect of Customer Services Quality and Online Reviews in Unive...Examining the Effect of Customer Services Quality and Online Reviews in Unive...
Examining the Effect of Customer Services Quality and Online Reviews in Unive...
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
 
Creative Web Design Company in Singapore
Creative Web Design Company in SingaporeCreative Web Design Company in Singapore
Creative Web Design Company in Singapore
 
The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...
 
BeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdfBeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdf
 

RubyEnRails2007 - Dr Nic Williams - DIY Syntax

  • 2. $ irb >> $KCODE = quot;uquot; >> quot;303274quot; => quot;üquot;
  • 3. Isn’t this nicer? >> U00FC => quot;üquot;
  • 4. $ sudo gem install charesc $ irb >> $KCODE = quot;uquot; >> require 'rubygems' >> require 'charesc' >> quot;charesc is made by Martin D#{U00FC}rstquot; => quot;charesc is made by Martin Dürstquot; >> U00FC => quot;üquot; >> quot;303274quot; => quot;üquot; charesc
  • 5. Active Records SELECT * FROM conferences WHERE (start_date > '2007-06-07') # But, much nicer is...
  • 6. Active Records SELECT * FROM conferences WHERE (start_date > '2007-06-07') # But, much nicer is... Conference.find(:all, :conditions => [‘start_date > ?’,Date.today])
  • 7. Active Records SELECT conferences.quot;idquot; AS t0_r0, conferences.quot;namequot; AS t0_r2, ..., conference_sessions.quot;idquot; AS t1_r0, conference_sessions.quot;conference_idquot; AS t1_r1, ... FROM conferences LEFT OUTER JOIN conference_sessions ON conference_sessions.conference_id = conferences.id WHERE (start_date < '2007-05-26') # But, definitely easier and nicer is...
  • 8. Active Records SELECT conferences.quot;idquot; AS t0_r0, conferences.quot;namequot; AS t0_r2, ..., conference_sessions.quot;idquot; AS t1_r0, conference_sessions.quot;conference_idquot; AS t1_r1, ... FROM conferences LEFT OUTER JOIN conference_sessions ON conference_sessions.conference_id = conferences.id WHERE (start_date < '2007-05-26') # But, definitely easier and nicer is... Conference.find(:all, :conditions => ['start_date < ?', Date.today], :include => :conference_sessions)
  • 9. Sexy Syntax ActiveRecords - no SQL ... + marshalling to objects
  • 10. Sexy Syntax Convenient Code
  • 11. Schemas create_table :conferences do |t| t.fkey :user t.string :name, :limit => 50 t.text :description t.date :start_date, :end_date t.auto_dates end # instead of... I can never remember SQL syntax
  • 12. Schemas create_table :conferences do |t| t.fkey :user t.string :name, :limit => 50 t.text :description t.date :start_date, :end_date t.auto_dates end # instead of... Look up SQL on I can never remember SQL syntax
  • 13. Composite Primary Keys ProductHistory.find(:first, :conditions => ['id = ? and start_date = ?', 56, Date.new(2000,5,5)]) # rather... What about Ruby syntax improving on other Ruby syntax?
  • 14. Composite Primary Keys ProductHistory.find(:first, :conditions => ['id = ? and start_date = ?', 56, Date.new(2000,5,5)]) # rather... ProductHistory.find(56, Date.new(2000,5,5)) What about Ruby syntax class ProductHistory < ActiveRecord::Base improving on other Ruby set_primary_keys :id, :start_date syntax? end
  • 15. What’s this do? #1 Nice syntax can quickly tell you want the code will does @user.conference_sessions_for(@conference)
  • 16. What’s this do? #1 Nice syntax can quickly tell you want the code will does @user.conference_sessions_for(@conference) # Returns all ConferenceSessions # for a user at a conference
  • 17. What’s this do? #2 @conference_attendees.map_id_and_login_and_full_name
  • 18. What’s this do? #2 @conference_attendees.map_id_and_login_and_full_name # map {|att| [att.id, att.login, att.full_name]}
  • 19. What’s this do? #3 User.find(params[:id])
  • 20. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id])
  • 21. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id]) @to_user.update(@from_db::User.find(params[:id]))
  • 22. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id]) @to_user.update(@from_db::User.find(params[:id])) # Copies a User from one database to another # see Magic Multi-Connection # http://magicmodels.rubyforge.org
  • 23. Let’s see how they work...
  • 24. What’s this do? #1 Nice syntax can quickly tell you want the code will does @user.conference_sessions_for(@conference)
  • 25. What’s this do? #1 Nice syntax can quickly tell you want the code will does @user.conference_sessions_for(@conference) # Returns all ConferenceSessions # for a user at a conference
  • 26. What’s this do? #1 class User < ActiveRecord::Base has_many :conference_sessions def conference_sessions_for(conference) conference_sessions.find(:all, :conditions => ['conference_id = ?', conference]) end end No meta-magic, but it gives nice syntax
  • 27. What’s this do? #2 @attendees.map_by_id_and_login_and_full_name # map {|att| [att.id, att.login, att.full_name]}
  • 28. Cute ways to use #map @users = User.find(:all) @users.map {|user| user.login} # => ['drnic', 'topfunky', 'dhh']
  • 29. Cute ways to use #map @users = User.find(:all) @users.map {|user| user.login} # => ['drnic', 'topfunky', 'dhh'] @users.map &:login # => ['drnic', 'topfunky', 'dhh']
  • 30. Cute ways to use #map @users = User.find(:all) @users.map {|user| user.login} # => ['drnic', 'topfunky', 'dhh'] @users.map &:login # => ['drnic', 'topfunky', 'dhh'] # but it gets ugly when you chain them... @users.map(&:login).map(&:size) # => [5, 8, 3]
  • 31. Cute ways to use #map # So, instead of... @users.map(&:login).map(&:size) # We might like... @users.map_login.map_size
  • 32. Remember find_by_xxx ? def method_missing(method_id, *arguments) pattern = /^find_(all_by|by)_([_a-zA-Z]w*)$/ if match = pattern.match(method_id.to_s) finder = determine_finder(match) # from active_record/base.rb, line 1190
  • 33. Dissecting the request def method_missing(method, *args, &block) pattern = /(map|select|...)_by_([w_]+??)/ if (match = method.match(pattern)) iterator, callmethod = match[1], match[2] # changed ‘find’ to ‘map’ # or select, reject, each, collect...
  • 34. Iterating the request # continued... iterator, callmethod = match[1], match[2] self.send(iterator) {|obj| obj.send callmethod } # @array.map_by_foo # callmethod => ‘foo’ # #foo invoked on each element of Array
  • 35. Iterating many callmethods # continued... iterator, callmethod = match[1], match[2] callmethods = callmethod.split('_and_') callmethods.map do |callmethod| self.send(iterator) {|obj| obj.send callmethod } end # @array.map_by_foo_and_bar # callmethods => [‘foo’, ‘bar’] # #foo and #bar invoked on each element of Array
  • 36. map_by_method gem # for complete source: $ gem install map_by_method $ mate $RUBYGEMS_PATH/map_by_method-0.6.0/lib/map_by_method.rb
  • 37. map_by_method gem # for complete source: $ gem install map_by_method $ mate $RUBYGEMS_PATH/map_by_method-0.6.0/lib/map_by_method.rb # add the following to your ~/.irbrc require 'map_by_method'
  • 38. What’s this do? #3 User.find(params[:id])
  • 39. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id])
  • 40. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id]) @to_user.update(@from_db::User.find(params[:id]))
  • 41. What’s this do? #3 @to_user = @target_db::User.find(params[:id]) User.find(params[:id]) @to_user.update(@from_db::User.find(params[:id])) # Copies a User from one database to another # see Magic Multi-Connection # http://magicmodels.rubyforge.org
  • 43. MMC - alternate ideas @db::User.find(params[:id]) # but I would have preferred... User.find(params[:id]).from_db(@db)
  • 44. MMC - alternate ideas @db::User.find(params[:id]) # but I would have preferred... User.find(params[:id]).from_db(@db) # but we’d need FindProxies # like AssociationProxies
  • 45. But what does this mean? @db::User
  • 46. class creator helper class Module def create_class(class_name, superclass = Object, &block) klass = Class.new superclass, &block self.const_set class_name, klass end end >> module Connection; end >> Connection.create_class 'User' => Connection::User
  • 47. class creator helper class Module def create_class(class_name, superclass = Object, &block) klass = Class.new superclass, &block self.const_set class_name, klass end end >> module Connection; end >> Connection.create_class 'User' => Connection::User @db::User
  • 48. But...the class... “when to create it?” When you ask for it!
  • 49. const_missing class Module alias :old_const_missing :const_missing def const_missing(const_id) return old_const_missing(const_id) rescue nil target_class = quot;::#{const_id}quot;.constantize rescue nil raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class create_class(const_id, target_class) end end
  • 50. const_missing class Module alias :old_const_missing :const_missing def const_missing(const_id) return old_const_missing(const_id) rescue nil target_class = quot;::#{const_id}quot;.constantize rescue nil raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class create_class(const_id, target_class) end end magic multi-connections
  • 51. Picks up root classes class Person; end module Remote establish_connection :other end >> Remote::Person.superclass => Person
  • 52. const_missing class Module def const_missing(const_id) return old_const_missing(class_id) rescue nil table_name = DrNicMagicModels::Schema.models[const_id] raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name create_class(class_id, ActiveRecord::Base) do set_table_name table_name end end end “Does the class name match to a table name?”
  • 53. const_missing class Module def const_missing(const_id) return old_const_missing(class_id) rescue nil table_name = DrNicMagicModels::Schema.models[const_id] raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name create_class(class_id, ActiveRecord::Base) do set_table_name table_name end end dr nic’s magic models end “Does the class name match to a table name?”
  • 54. const_missing >> U00FC => quot;üquot;
  • 55. const_missing def const_missing(const) if const.to_s =~ /^((U( [0-9ABCEF][0-9A-F]{3} # general BMP | D[0-7][0-9A-F]{2} # excluding surrogates | [1-9A-F][0-9A-F]{4} # planes 1-15 | 10 [0-9A-F]{4} # plane 16 ) )* ) $/ix unescaped = $1.split(/[Uu]/)[1..-1].collect do |hex| hex.to_i(16) end.pack('U*')
  • 57. Enjoy En ! drnicwilliams.com by Dr Nic