Wider Than Rails:Lightweight Ruby    Solutions Alexey Nayden, EvilMartians.com          RubyC 2011
Lightweight != FastLightweight ≈ Simple
Less code         =Easier to maintain         =        (often)      Faster
Motives to travel light•   Production performance•   Complexity overhead•   Learning curve•   More flexibility•   Self-impr...
Do you always need all$ ls      of that?app/config/db/doc/Gemfilelib/logpublic/RakefileREADMEscript/spec/test/tmp/vendor/w...
Do you always need all$ ls      of that?app/config/db/doc/Gemfilelib/logpublic/RakefileREADMEscript/spec/test/tmp/vendor/w...
Lightweight plan• Replace components of your framework• Inject lightweight tools• Migrate to a different platform• Dont fo...
ActiveRecord? Sequel!•   http://sequel.rubyforge.org•   Sequel is a gem providing both raw SQL and neat    ORM interfaces•...
Sequel ORMclass UsersController < ApplicationController  before_filter :find_user, :except => [:create]  def create   @user ...
Sequel Modelclass User < Sequel::Model  one_to_many :comments  subset(:active){comments_count > 20} plugin :validation_hel...
Raw SQLDB.fetch("SELECT * FROM albums WHERE name LIKE :pattern", :pattern=>A%) do |row|  puts row[:name]endDB.run "CREATE ...
Benchmarks
Clean frontend with         Zepto.js•   http://zeptojs.com•   JS framework for with a jQ-compatible syntax    and API•   P...
Good old $$(p>span).html(Hello, RubyC).css(color:red);      Well-known syntax$(p).bind(click, function(){  $(span, this).c...
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 Ru...
Rack•   You need to have an object with a method    call(env)•   It should return an array with 3 elements    [status_code...
Rack App Exampleclass ServerLoad  def call(env)    [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d  "]]  e...
Metal. Rack on Rails•   ActionController::Metal is a way to get a valid Rack    app from a controller•   A bit more comfor...
Metallic APIclass ApiController < ActionController::Metal  include AbstractController::Callbacks  include ActionController...
Sinatra•   Sinatra should be considered as a compact    framework (however they prefer calling it DSL)    replacing Action...
Sinatrarequire rubygemsrequire sinatraget / do  haml :indexendpost /signup do  Spam.deliver(params[:email])endmime :json, ...
Padrino. DSL evolves to     a framework• http://www.padrinorb.com/• Based on a Sinatra and brings LIKE-A-BOSS  comfort to ...
Padrino blog$ padrino g project sample_blog -t shoulda -e haml     -c sass -s jquery -d activerecord -b  class SampleBlog ...
Posts controllerSampleBlog.controllers :posts do  get :index, :provides => [:html, :rss, :atom] do    @posts = Post.all(:o...
A little bit of useless     benchmarking• We take almost plain «Hello World»  application and run  ab ‐c 10 ‐n 1000• rack ...
ToolsThey dont 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...
rbenv• https://github.com/sstephenson/rbenv• Small, quick, doesnt modify shell  commands, UNIX-way• rbenv global 1.9.2‐p29...
One more thing...
Ruby is not a silver            bulletYou should always consider different platforms and   languages: Erlang, Scala, .NET ...
Ruby is not a silver            bulletYou should always consider different platforms and   languages: Erlang, Scala, .NET ...
Questions?alexey.nayden@evilmartians.com
Upcoming SlideShare
Loading in...5
×

Wider than rails

1,826

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,826
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
8
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Wider than rails

    1. 1. Wider Than Rails:Lightweight Ruby Solutions Alexey Nayden, EvilMartians.com RubyC 2011
    2. 2. Lightweight != FastLightweight ≈ Simple
    3. 3. Less code =Easier to maintain = (often) Faster
    4. 4. Motives to travel light• Production performance• Complexity overhead• Learning curve• More flexibility• Self-improvement
    5. 5. Do you always need all$ ls of that?app/config/db/doc/Gemfilelib/logpublic/RakefileREADMEscript/spec/test/tmp/vendor/www/Gemfile.lock.rspecconfig.ru
    6. 6. Do you always need all$ ls of that?app/config/db/doc/Gemfilelib/logpublic/RakefileREADMEscript/spec/test/tmp/vendor/www/Gemfile.lock.rspecconfig.ru
    7. 7. Lightweight plan• Replace components of your framework• Inject lightweight tools• Migrate to a different platform• Dont forget to be consistent
    8. 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. 9. Sequel ORMclass UsersController < ApplicationController before_filter :find_user, :except => [:create] def create @user = User.new(params[:user]) end protected def find_user @user = User[params[:id]] endend
    10. 10. Sequel Modelclass 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 theres a plugin super # for timestamping endend
    11. 11. Raw SQLDB.fetch("SELECT * FROM albums WHERE name LIKE :pattern", :pattern=>A%) do |row| puts row[:name]endDB.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)
    12. 12. Benchmarks
    13. 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. 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. 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. 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. 17. Rack App Exampleclass ServerLoad def call(env) [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d "]] endend
    18. 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. 19. Metallic APIclass 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 endend
    20. 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. 21. Sinatrarequire rubygemsrequire sinatraget / do haml :indexendpost /signup do Spam.deliver(params[:email])endmime :json, application/jsonget /events/recent.json do content_type :json Event.recent.to_jsonend
    22. 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. 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. 24. Posts controllerSampleBlog.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 endend
    25. 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. 26. ToolsThey dont need to be huge and slow
    27. 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. 28. rbenv• https://github.com/sstephenson/rbenv• Small, quick, doesnt modify shell commands, UNIX-way• rbenv global 1.9.2‐p290 cd /path/to/app rbenv local jruby‐1.6.4
    29. 29. One more thing...
    30. 30. Ruby is not a silver bulletYou should always consider different platforms and languages: Erlang, Scala, .NET and even C++
    31. 31. Ruby is not a silver bulletYou should always consider different platforms and languages: Erlang, Scala, .NET and even C++ Dont miss Timothy Tsvetkovs speech tomorrow
    32. 32. Questions?alexey.nayden@evilmartians.com
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×