SlideShare una empresa de Scribd logo
1 de 32
Wider Than Rails:
Lightweight Ruby
    Solutions
 Alexey Nayden, EvilMartians.com
          RubyC 2011
Lightweight != Fast

Lightweight ≈ Simple
Less code
         =
Easier to maintain
         =
        (often)


      Faster
Motives to travel light

•   Production performance

•   Complexity overhead

•   Learning curve

•   More flexibility

•   Self-improvement
Do you always need all
$ ls
      of that?
app/
config/
db/
doc/
Gemfile
lib/
log
public/
Rakefile
README
script/
spec/
test/
tmp/
vendor/
www/
Gemfile.lock
.rspec
config.ru
Do you always need all
$ ls
      of that?
app/
config/
db/
doc/
Gemfile
lib/
log
public/
Rakefile
README
script/
spec/
test/
tmp/
vendor/
www/
Gemfile.lock
.rspec
config.ru
Lightweight plan

• Replace components of your framework
• Inject lightweight tools
• Migrate to a different platform
• Don't forget to be consistent
ActiveRecord? Sequel!

•   http://sequel.rubyforge.org

•   Sequel is a gem providing both raw SQL and neat
    ORM interfaces

•   18 DBMS support out of the box

•   25—50% faster than ActiveRecord

•   100% ActiveModel compliant
Sequel ORM
class UsersController < ApplicationController
  before_filter :find_user, :except => [:create]
  def create
   @user = User.new(params[:user])
  end
  protected
   def find_user
     @user = User[params[:id]]
   end
end
Sequel Model
class User < Sequel::Model
  one_to_many :comments
  subset(:active){comments_count > 20}

 plugin :validation_helpers
 def validate
   super
   validates_presence [:email, :name]
   validates_unique :email
   validates_integer :age if new?
 end

  def before_create
    self.created_at ||= Time.now # however there's a plugin
    super                        # for timestamping
  end
end
Raw SQL
DB.fetch("SELECT * FROM albums WHERE name LIKE :pattern", :pattern=>'A%') do |row|
  puts row[:name]
end

DB.run "CREATE TABLE albums (id integer primary key, name varchar(255))"

db(:legacy).fetch("
      SELECT
      (SELECT count(*) FROM activities WHERE
            ACTION = 'logged_in'
            AND
            DATE(created_at) BETWEEN DATE(:start) AND DATE(:end)
       ) AS login_count,
      (SELECT count(*) FROM users WHERE
        (DATE(created_at) BETWEEN DATE(:start) AND DATE(:end))
        AND
        (activated_at IS NOT NULL)
      ) AS user_count",
 :start => start_date, :end => end_date)
Benchmarks
Clean frontend with
         Zepto.js
•   http://zeptojs.com

•   JS framework for with a jQ-compatible syntax
    and API

•   Perfect for rich mobile (esp. iOS) web-apps, but
    works in any modern browser except IE

•   7.5 Kb at the moment (vs. 31 Kb jQ)

•   Officially — beta, but used at mobile version of
    Groupon production-ready
Good old $
$('p>span').html('Hello, RubyC').css('color:red');




      Well-known syntax
$('p').bind('click', function(){
  $('span', this).css('color:red');
});



Touch UI? No problem!
$('some   selector').tap(function(){ ... });
$('some   selector').doubleTap(function(){ ... });
$('some   selector').swipeRight(function(){ ... });
$('some   selector').pinch(function(){ ... });
Xtra Xtra Small: Rack

• Rack is a specification of a minimal Ruby
  API that models HTTP
• One might say Rack is a CGI in a Ruby
  world
• Only connects a webserver with your
  «app» (actually it can be just a lambda!)
Rack
•   You need to have an object with a method
    call(env)

•   It should return an array with 3 elements
    [status_code, headers, body]

•   So now you can connect it with any webserver
    that supports Rack
    require ‘thin’
    Rack::Handler::Thin.run(app, :Port => 4000)

•   Lightweight webapp completed
Rack App Example
class ServerLoad
  def call(env)
    [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d ' '"]]
  end
end
Metal. Rack on Rails
•   ActionController::Metal is a way to get a valid Rack
    app from a controller

•   A bit more comfortable dealing with Rack inside
    Rails

•   You still can include any parts of ActionController
    stack inside your metal controller

•   Great for API`s
Metallic API
class ApiController < ActionController::Metal
  include AbstractController::Callbacks
  include ActionController::Helpers
  include Devise::Controllers::Helpers
  before_filter :require_current_user

  def history
    content_type = "application/json"
    recipient = User.find(params[:user_id])
    messages = Message.between(current_user, recipient)

    if params[:start_date]
      response_body = messages.after(params[:start_date]).to_json
    else
      response_body = messages.recent.to_json
    end

  end
end
Sinatra
•   Sinatra should be considered as a compact
    framework (however they prefer calling it DSL)
    replacing ActionController and router

•   You still can include ActiveRecord, ActiveSupport
    or on the other side — include Sinatra app inside
    Rails app

•   But you can also go light with Sequel / DataMapper
    and plaintext / XML / JSON output
Sinatra
require 'rubygems'
require 'sinatra'

get '/' do
  haml :index
end

post '/signup' do
  Spam.deliver(params[:email])
end

mime :json, 'application/json'
get '/events/recent.json' do
  content_type :json
  Event.recent.to_json
end
Padrino. DSL evolves to
     a framework
• http://www.padrinorb.com/
• Based on a Sinatra and brings LIKE-A-BOSS
  comfort to a Sinatra development process
• Fully supports 6 ORMs, 5 JS libs, 2
  rendering engines, 6 test frameworks, 2
  stylesheet engines and 2 mocking libs out
  of the box
• Still remains quick and simple
Padrino blog
$ padrino g project sample_blog -t shoulda -e haml 
    -c sass -s jquery -d activerecord -b
  class SampleBlog < Padrino::Application
    register Padrino::Helpers
    register Padrino::Mailer
    register SassInitializer

    get "/" do
      "Hello World!"
    end

    get :about, :map => '/about_us' do
      render :haml, "%p This is a sample blog"
    end

  end
Posts controller
SampleBlog.controllers :posts do
  get :index, :provides => [:html, :rss, :atom] do
    @posts = Post.all(:order => 'created_at desc')
    render 'posts/index'
  end

  get :show, :with => :id do
    @post = Post.find_by_id(params[:id])
    render 'posts/show'
  end
end
A little bit of useless
     benchmarking
• We take almost plain «Hello World»
  application and run
  ab ‐c 10 ‐n 1000
• rack 1200 rps
• sinatra 600 rps
• padrino 570 rps
• rails 140 rps
Tools
They don't need to be huge and slow
Pow
• http://pow.cx/
• A 37signals Rack-based webserver for
  developer needs
• One-line installer, unobtrusive, fast and only
  serves web-apps, nothing else
• cd ~/.pow
  ln ‐s /path/to/app
rbenv

• https://github.com/sstephenson/rbenv
• Small, quick, doesn't modify shell
  commands, UNIX-way
• rbenv global 1.9.2‐p290
  cd /path/to/app
  rbenv local jruby‐1.6.4
One more thing...
Ruby is not a silver
            bullet
You should always consider different platforms and
   languages: Erlang, Scala, .NET and even C++
Ruby is not a silver
            bullet
You should always consider different platforms and
   languages: Erlang, Scala, .NET and even C++

 Don't miss Timothy Tsvetkov's speech
              tomorrow
Questions?
alexey.nayden@evilmartians.com

Más contenido relacionado

La actualidad más candente

Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 

La actualidad más candente (20)

Ansible module development 101
Ansible module development 101Ansible module development 101
Ansible module development 101
 
Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node Driver
 
Celery introduction
Celery introductionCelery introduction
Celery introduction
 
Ansible 202
Ansible 202Ansible 202
Ansible 202
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
How to create a libcloud driver from scratch
How to create a libcloud driver from scratchHow to create a libcloud driver from scratch
How to create a libcloud driver from scratch
 
How to create a libcloud driver from scratch
How to create a libcloud driver from scratchHow to create a libcloud driver from scratch
How to create a libcloud driver from scratch
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 

Destacado

Haml/Sassを使って履歴書を書くためのn個の方法
Haml/Sassを使って履歴書を書くためのn個の方法Haml/Sassを使って履歴書を書くためのn個の方法
Haml/Sassを使って履歴書を書くためのn個の方法
Tomohiro Nishimura
 
Sequel — механизм доступа к БД, написанный на Ruby
Sequel — механизм доступа к БД, написанный на RubySequel — механизм доступа к БД, написанный на Ruby
Sequel — механизм доступа к БД, написанный на Ruby
Alexey Nayden
 
развертывание среды Rails (антон веснин, Locum Ru)
развертывание среды Rails (антон веснин, Locum Ru)развертывание среды Rails (антон веснин, Locum Ru)
развертывание среды Rails (антон веснин, Locum Ru)
guest40e031
 

Destacado (8)

Wider than rails
Wider than railsWider than rails
Wider than rails
 
Технические аспекты знакоства с девушкой в Интернете
Технические аспекты знакоства с девушкой в ИнтернетеТехнические аспекты знакоства с девушкой в Интернете
Технические аспекты знакоства с девушкой в Интернете
 
Haml/Sassを使って履歴書を書くためのn個の方法
Haml/Sassを使って履歴書を書くためのn個の方法Haml/Sassを使って履歴書を書くためのn個の方法
Haml/Sassを使って履歴書を書くためのn個の方法
 
Хэши в ruby
Хэши в rubyХэши в ruby
Хэши в ruby
 
Sequel — механизм доступа к БД, написанный на Ruby
Sequel — механизм доступа к БД, написанный на RubySequel — механизм доступа к БД, написанный на Ruby
Sequel — механизм доступа к БД, написанный на Ruby
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»
 
развертывание среды Rails (антон веснин, Locum Ru)
развертывание среды Rails (антон веснин, Locum Ru)развертывание среды Rails (антон веснин, Locum Ru)
развертывание среды Rails (антон веснин, Locum Ru)
 
Top10 доводов против языка Ruby
Top10 доводов против языка RubyTop10 доводов против языка Ruby
Top10 доводов против языка Ruby
 

Similar a Wider than rails

Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
Avi Kedar
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 

Similar a Wider than rails (20)

Rack
RackRack
Rack
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
LA Ember.js Meetup, Jan 2017
LA Ember.js Meetup, Jan 2017LA Ember.js Meetup, Jan 2017
LA Ember.js Meetup, Jan 2017
 
Building production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stackBuilding production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stack
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Sinatra
SinatraSinatra
Sinatra
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Serverless in-action
Serverless in-actionServerless in-action
Serverless in-action
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 

Último

+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
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - 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, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 

Wider than rails

  • 1. Wider Than Rails: Lightweight Ruby Solutions Alexey Nayden, EvilMartians.com RubyC 2011
  • 3. Less code = Easier to maintain = (often) Faster
  • 4. Motives to travel light • Production performance • Complexity overhead • Learning curve • More flexibility • Self-improvement
  • 5. Do you always need all $ ls of that? app/ config/ db/ doc/ Gemfile lib/ log public/ Rakefile README script/ spec/ test/ tmp/ vendor/ www/ Gemfile.lock .rspec config.ru
  • 6. Do you always need all $ ls of that? app/ config/ db/ doc/ Gemfile lib/ log public/ Rakefile README script/ spec/ test/ tmp/ vendor/ www/ Gemfile.lock .rspec config.ru
  • 7. Lightweight plan • Replace components of your framework • Inject lightweight tools • Migrate to a different platform • Don't forget to be consistent
  • 8. ActiveRecord? Sequel! • http://sequel.rubyforge.org • Sequel is a gem providing both raw SQL and neat ORM interfaces • 18 DBMS support out of the box • 25—50% faster than ActiveRecord • 100% ActiveModel compliant
  • 9. Sequel ORM class UsersController < ApplicationController before_filter :find_user, :except => [:create] def create @user = User.new(params[:user]) end protected def find_user @user = User[params[:id]] end end
  • 10. Sequel Model class User < Sequel::Model one_to_many :comments subset(:active){comments_count > 20} plugin :validation_helpers def validate super validates_presence [:email, :name] validates_unique :email validates_integer :age if new? end def before_create self.created_at ||= Time.now # however there's a plugin super # for timestamping end end
  • 11. Raw SQL DB.fetch("SELECT * FROM albums WHERE name LIKE :pattern", :pattern=>'A%') do |row| puts row[:name] end DB.run "CREATE TABLE albums (id integer primary key, name varchar(255))" db(:legacy).fetch(" SELECT (SELECT count(*) FROM activities WHERE ACTION = 'logged_in' AND DATE(created_at) BETWEEN DATE(:start) AND DATE(:end) ) AS login_count, (SELECT count(*) FROM users WHERE (DATE(created_at) BETWEEN DATE(:start) AND DATE(:end)) AND (activated_at IS NOT NULL) ) AS user_count", :start => start_date, :end => end_date)
  • 13. Clean frontend with Zepto.js • http://zeptojs.com • JS framework for with a jQ-compatible syntax and API • Perfect for rich mobile (esp. iOS) web-apps, but works in any modern browser except IE • 7.5 Kb at the moment (vs. 31 Kb jQ) • Officially — beta, but used at mobile version of Groupon production-ready
  • 14. Good old $ $('p>span').html('Hello, RubyC').css('color:red'); Well-known syntax $('p').bind('click', function(){ $('span', this).css('color:red'); }); Touch UI? No problem! $('some selector').tap(function(){ ... }); $('some selector').doubleTap(function(){ ... }); $('some selector').swipeRight(function(){ ... }); $('some selector').pinch(function(){ ... });
  • 15. Xtra Xtra Small: Rack • Rack is a specification of a minimal Ruby API that models HTTP • One might say Rack is a CGI in a Ruby world • Only connects a webserver with your «app» (actually it can be just a lambda!)
  • 16. Rack • You need to have an object with a method call(env) • It should return an array with 3 elements [status_code, headers, body] • So now you can connect it with any webserver that supports Rack require ‘thin’ Rack::Handler::Thin.run(app, :Port => 4000) • Lightweight webapp completed
  • 17. Rack App Example class ServerLoad def call(env) [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d ' '"]] end end
  • 18. Metal. Rack on Rails • ActionController::Metal is a way to get a valid Rack app from a controller • A bit more comfortable dealing with Rack inside Rails • You still can include any parts of ActionController stack inside your metal controller • Great for API`s
  • 19. Metallic API class ApiController < ActionController::Metal include AbstractController::Callbacks include ActionController::Helpers include Devise::Controllers::Helpers before_filter :require_current_user def history content_type = "application/json" recipient = User.find(params[:user_id]) messages = Message.between(current_user, recipient) if params[:start_date] response_body = messages.after(params[:start_date]).to_json else response_body = messages.recent.to_json end end end
  • 20. Sinatra • Sinatra should be considered as a compact framework (however they prefer calling it DSL) replacing ActionController and router • You still can include ActiveRecord, ActiveSupport or on the other side — include Sinatra app inside Rails app • But you can also go light with Sequel / DataMapper and plaintext / XML / JSON output
  • 21. Sinatra require 'rubygems' require 'sinatra' get '/' do haml :index end post '/signup' do Spam.deliver(params[:email]) end mime :json, 'application/json' get '/events/recent.json' do content_type :json Event.recent.to_json end
  • 22. Padrino. DSL evolves to a framework • http://www.padrinorb.com/ • Based on a Sinatra and brings LIKE-A-BOSS comfort to a Sinatra development process • Fully supports 6 ORMs, 5 JS libs, 2 rendering engines, 6 test frameworks, 2 stylesheet engines and 2 mocking libs out of the box • Still remains quick and simple
  • 23. Padrino blog $ padrino g project sample_blog -t shoulda -e haml -c sass -s jquery -d activerecord -b class SampleBlog < Padrino::Application register Padrino::Helpers register Padrino::Mailer register SassInitializer get "/" do "Hello World!" end get :about, :map => '/about_us' do render :haml, "%p This is a sample blog" end end
  • 24. Posts controller SampleBlog.controllers :posts do get :index, :provides => [:html, :rss, :atom] do @posts = Post.all(:order => 'created_at desc') render 'posts/index' end get :show, :with => :id do @post = Post.find_by_id(params[:id]) render 'posts/show' end end
  • 25. A little bit of useless benchmarking • We take almost plain «Hello World» application and run ab ‐c 10 ‐n 1000 • rack 1200 rps • sinatra 600 rps • padrino 570 rps • rails 140 rps
  • 26. Tools They don't need to be huge and slow
  • 27. Pow • http://pow.cx/ • A 37signals Rack-based webserver for developer needs • One-line installer, unobtrusive, fast and only serves web-apps, nothing else • cd ~/.pow ln ‐s /path/to/app
  • 28. rbenv • https://github.com/sstephenson/rbenv • Small, quick, doesn't modify shell commands, UNIX-way • rbenv global 1.9.2‐p290 cd /path/to/app rbenv local jruby‐1.6.4
  • 30. Ruby is not a silver bullet You should always consider different platforms and languages: Erlang, Scala, .NET and even C++
  • 31. Ruby is not a silver bullet You should always consider different platforms and languages: Erlang, Scala, .NET and even C++ Don't miss Timothy Tsvetkov's speech tomorrow

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n