SlideShare a Scribd company logo
Wider Than Rails:
                          Lightweight Ruby
                              Solutions
                           Alexey Nayden, EvilMartians.com
                                    RubyC 2011




суббота, 5 ноября 11 г.
Lightweight != Fast

                          Lightweight ≈ Simple


суббота, 5 ноября 11 г.
Less code
                                   =
                          Easier to maintain
                                   =
                                  (often)


                                Faster

суббота, 5 ноября 11 г.
Motives to travel light

                     •    Production performance

                     •    Complexity overhead

                     •    Learning curve

                     •    More flexibility

                     •    Self-improvement




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
Lightweight plan

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

суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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



суббота, 5 ноября 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)




суббота, 5 ноября 11 г.
Benchmarks




суббота, 5 ноября 11 г.
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

суббота, 5 ноября 11 г.
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(){ ... });



суббота, 5 ноября 11 г.
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!)



суббота, 5 ноября 11 г.
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



суббота, 5 ноября 11 г.
Rack App Example
         class ServerLoad
           def call(env)
             [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d ' '"]]
           end
         end




суббота, 5 ноября 11 г.
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



суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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
суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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




суббота, 5 ноября 11 г.
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
суббота, 5 ноября 11 г.
Tools
                          They don't need to be huge and slow




суббота, 5 ноября 11 г.
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



суббота, 5 ноября 11 г.
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



суббота, 5 ноября 11 г.
One more thing...


суббота, 5 ноября 11 г.
Ruby is not a silver
                                bullet
            You should always consider different platforms and
               languages: Erlang, Scala, .NET and even C++




суббота, 5 ноября 11 г.
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

суббота, 5 ноября 11 г.
Questions?
                          alexey.nayden@evilmartians.com




суббота, 5 ноября 11 г.

More Related Content

PDF
Технические аспекты знакоства с девушкой в Интернете
PPTX
антон веснин Rails Application Servers
KEY
Sequel — механизм доступа к БД, написанный на Ruby
PDF
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
PPTX
Введение в Akka
PDF
Превышаем скоростные лимиты с Angular 2
PDF
«Как перестать отлаживать асинхронные вызовы и начать жить»​
PDF
How to build solid CI-CD pipeline / Илья Беда (beda.software)
Технические аспекты знакоства с девушкой в Интернете
антон веснин Rails Application Servers
Sequel — механизм доступа к БД, написанный на Ruby
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
Введение в Akka
Превышаем скоростные лимиты с Angular 2
«Как перестать отлаживать асинхронные вызовы и начать жить»​
How to build solid CI-CD pipeline / Илья Беда (beda.software)

What's hot (20)

PDF
Работа с Akka Сluster, @afiskon, scalaby#14
PPTX
Event Machine
PDF
Чуть сложнее чем Singleton: аннотации, IOC, АОП
PDF
Продуктовые проблемы при создании очередной Docker PaaS / Владимир Ярцев (Cas...
PDF
Подходы и технологии, используемые в разработке iOS-клиента Viber, Кирилл Лаш...
PPTX
Вебинар на тему знакомство с Ansible. популярные практики и ошибки
KEY
Chef коротко об инфраструктуре
PDF
Продвинутое использование Celery — Александр Кошелев
PDF
MariaDB 10.1 - что нового.
PDF
Erlang tasty & useful stuff
PPTX
Переезжаем с Zabbix на Prometheus / Василий Озеров (fevlake)
PDF
Scala On Rest
PDF
Вадим Челышов, Scala Engineer : Все ненавидят SBT
PDF
Курс Java-2016. Занятие 09. Web
PPTX
Java 8. Autotests in a functional way.
PDF
Эффективная отладка репликации MySQL
PPTX
Тестирование через мониторинг или холакратия на практике / Максим Чистяков (U...
PPTX
Неочевидные детали при запуске HTTPS в OK.Ru / Андрей Домась (Одноклассники)
PPTX
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
Работа с Akka Сluster, @afiskon, scalaby#14
Event Machine
Чуть сложнее чем Singleton: аннотации, IOC, АОП
Продуктовые проблемы при создании очередной Docker PaaS / Владимир Ярцев (Cas...
Подходы и технологии, используемые в разработке iOS-клиента Viber, Кирилл Лаш...
Вебинар на тему знакомство с Ansible. популярные практики и ошибки
Chef коротко об инфраструктуре
Продвинутое использование Celery — Александр Кошелев
MariaDB 10.1 - что нового.
Erlang tasty & useful stuff
Переезжаем с Zabbix на Prometheus / Василий Озеров (fevlake)
Scala On Rest
Вадим Челышов, Scala Engineer : Все ненавидят SBT
Курс Java-2016. Занятие 09. Web
Java 8. Autotests in a functional way.
Эффективная отладка репликации MySQL
Тестирование через мониторинг или холакратия на практике / Максим Чистяков (U...
Неочевидные детали при запуске HTTPS в OK.Ru / Андрей Домась (Одноклассники)
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
Ad

Viewers also liked (7)

KEY
Haml/Sassを使って履歴書を書くためのn個の方法
KEY
Wider than rails
PDF
Mini Rails Framework
PDF
Хэши в ruby
PDF
«Работа с базами данных с использованием Sequel»
PPTX
развертывание среды Rails (антон веснин, Locum Ru)
ODP
Top10 доводов против языка Ruby
Haml/Sassを使って履歴書を書くためのn個の方法
Wider than rails
Mini Rails Framework
Хэши в ruby
«Работа с базами данных с использованием Sequel»
развертывание среды Rails (антон веснин, Locum Ru)
Top10 доводов против языка Ruby
Ad

Similar to Wider than rails (20)

PPT
CodeFest 2012. Сидельников А. — Опыт создания DSL на Ruby. Где применить, как...
PDF
UWDC 2013, Yii2
PPT
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
PPT
Easy authcache 2 кэширование для pro. Родионов Игорь
PPTX
Scripting languages
PDF
Облачные технологии и виртуализация
PDF
REPL в Node.js: улучшаем быт разработчик
PDF
Scala, SBT & Play! for Rapid Application Development
PPT
Easy authcache 2 кеширование для pro родионов игорь
PPTX
Development of a plugin for VS Code that supports ACSL language.
PPT
Rupyru2007 Rastyagaev Ruby
PPTX
Применяем Ansible
PPTX
разработка бизнес приложений (7)
PDF
Romanova techforum bash
ODP
Чему мы можем научиться у Lisp'а?
PPTX
Hosting for forbes.ru_
PDF
Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh...
PPTX
Как приручить проектное окружение. PHP UG Minsk, июнь'2014
PDF
Истинный DevOps. Секрет 42.
CodeFest 2012. Сидельников А. — Опыт создания DSL на Ruby. Где применить, как...
UWDC 2013, Yii2
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
Easy authcache 2 кэширование для pro. Родионов Игорь
Scripting languages
Облачные технологии и виртуализация
REPL в Node.js: улучшаем быт разработчик
Scala, SBT & Play! for Rapid Application Development
Easy authcache 2 кеширование для pro родионов игорь
Development of a plugin for VS Code that supports ACSL language.
Rupyru2007 Rastyagaev Ruby
Применяем Ansible
разработка бизнес приложений (7)
Romanova techforum bash
Чему мы можем научиться у Lisp'а?
Hosting for forbes.ru_
Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh...
Как приручить проектное окружение. PHP UG Minsk, июнь'2014
Истинный DevOps. Секрет 42.

Wider than rails

  • 1. Wider Than Rails: Lightweight Ruby Solutions Alexey Nayden, EvilMartians.com RubyC 2011 суббота, 5 ноября 11 г.
  • 2. Lightweight != Fast Lightweight ≈ Simple суббота, 5 ноября 11 г.
  • 3. Less code = Easier to maintain = (often) Faster суббота, 5 ноября 11 г.
  • 4. Motives to travel light • Production performance • Complexity overhead • Learning curve • More flexibility • Self-improvement суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 7. Lightweight plan • Replace components of your framework • Inject lightweight tools • Migrate to a different platform • Don't forget to be consistent суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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) суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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(){ ... }); суббота, 5 ноября 11 г.
  • 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!) суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 17. Rack App Example class ServerLoad def call(env) [200, {"Content-Type" => "text/plain"}, ["uptime | cut -f 11 -d ' '"]] end end суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 26. Tools They don't need to be huge and slow суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 29. One more thing... суббота, 5 ноября 11 г.
  • 30. Ruby is not a silver bullet You should always consider different platforms and languages: Erlang, Scala, .NET and even C++ суббота, 5 ноября 11 г.
  • 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 суббота, 5 ноября 11 г.
  • 32. Questions? alexey.nayden@evilmartians.com суббота, 5 ноября 11 г.