SlideShare a Scribd company logo
Rails: Web API
       shaokun.wu@gmail.com


 Thanks to Leon Du and Rain Chen
You should start with...

• ruby 1.9.2
  Performance, Threads/Fibers, Encoding/Unicode...




• rails 3.1.0
  Asset pipeline, HTTP streaming, jQuery
Rails on Campus
https://github.com/kudelabs/roc-demo1
https://github.com/kudelabs/roc-demo2
Rails web api 开发
Rails web api 开发
GZRuby
http://groups.google.com/group/gzruby?lnk=srg
talk about...
• API
• API
•        API

•
•
Start Simple but Elegant
     http://localhost:3000/api/messages
   http://localhost:3000/api/messages/{id}
•   $ git clone git://github.com/kudelabs/roc-demo2.git

•   $ cd roc-demo2

•   $ bundle install

•   $ rake db:create

•   $ rake db:migrate

•   $ rails server

•   goto http://localhost:3000
•   $ rails generate controller api::messages
    apps/controllers/api/messages_controller.rb
    test/functional/api/messages_controller_test.rb
apps/controllers/api/messages_controller.rb
    class Api::MessagesController < ApplicationController
      # GET /api/messages.json
      def index
        @messages = Message.all

        respond_to do |format|
          format.json { render json: @messages }
        end
      end

      # GET /api/messages/1.json
      def show
        @message = Message.find(params[:id])

        respond_to do |format|
          format.json { render json: @message }
        end
      end
    end
curl http://localhost:3000/api/messages
Start Alone but
Test is Your Partner
     rake test:functionals
        rake test:units
     rake test:integration
test/functional/api/messages_controller_test.rb
   class Api::MessagesControllerTest < ActionController::TestCase
     setup do
       @message = messages(:one)
     end

    test "should get index" do
      get :index, format: :json
      assert_response :success
      assert_not_nil assigns(:messages)
    end

     test "should show message" do
       get :show, format: :json, id: @message.to_param
       assert_response :success
     end
   end
API
built-in Namespaced
     controllers
  http://localhost:3000/api/v2/messages

       Rocweibo::Application.routes.draw do
         namespace :api do
           resources :messages

           namespace :v2 do
             resources :messages
           end
         end
       end
test/functional/api/v2/messages_controller_test.rb
class Api::V2::MessagesController < Api::ApplicationController
  before_filter :authenticate, :only => :create

 ...

 # curl -X POST -H "Accept: application/json" --user shaokun.wu@gmail.com:a
 # http://localhost:3000/api/v2/messages -d "message[body]=abcdefg"
 def create
   @message = Message.new(params[:message])
   @message.user = @current_user
   @message.save!

    render json: @message
  end

  private
  def authenticate
    if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) }
      @current_user = user
    else
      request_http_basic_authentication
    end
  end
end
Keep Refactoring
whenever You could
  Don’t Repeat Yourself & Decoupling
class Api::V2::MessagesController < Api::ApplicationController
  ...

  private
  def authenticate
    if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) }
      @current_user = user
    else
      request_http_basic_authentication
    end
  end
end




class Api::ApplicationController < ActionController::Base
  private
  def authenticate
    if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) }
      @current_user = user
    else
      request_http_basic_authentication
    end
  end
end
/app/controllers/api/application_controller.rb
    class Api::ApplicationController < ActionController::Base
    end




 /app/controllers/application_controller.rb
      class ApplicationController < ActionController::Base
        helper_method :current_user, :logged_in?
        protect_from_forgery

        before_filter :require_logged_in
        ...
      end
Grape
A opinionated micro-framework for
  creating REST-like APIs in Ruby.
class Rocweibo::V1::API < Grape::API
  prefix 'api'
  version 'v1'

 resource :messages do
   get do
     Message.limit(20)
   end

    get ':id' do
      Message.find(params[:id])
    end
  end
end




                                  Rocweibo::Application.routes.draw do
                                    mount Rocweibo::V1::API => "/" # mount API routes
                                    ...
                                  end
Where to HOST your app?
No Easy Way to Host in China :(

•   Amazon EC2

•   Linode

•   DotCloud

•   Heroku
DotCloud
$ dotcloud push {myapp} {myrepopath}/
• $ dotcloud create rocdemo
• $ touch dotcloud.yml
• $ dotcloud push rocdemo .
• or
    $ dotcloud push -b mybranch rocdemo .
Deployment finished. Your application is available at the following URLs
www: http://rocdemo-limiru2n.dotcloud.com/
add mysql service
# just update the content of your dotcloud.yml
www:
  type: ruby                                      $ dotcloud info rocdemo
data:
  type: mysql                                     data:
                                                       config:
                                                           mysql_password: ...
                                                       instances: 1
                                                       type: mysql
# also, update the content of your database.yml
                                                  www:
production:
                                                       config:
  adapter: mysql2
                                                           rack-env: production
  encoding: utf8
                                                           ruby-version: 1.9.2
  reconnect: false
                                                       instances: 1
  database: roc_demo2_production
                                                       type: ruby
  pool: 5
                                                       url: http://rocdemo-limiru2n.dotclo
  username: root
  password: ...
  port: 14895
  host: rocdemo-LIMIRU2N.dotcloud.com
• dotcloud logs rocdemo.www
• dotcloud ssh rocdemo.www
• dotcloud info rocdemo
Rails Admin
•   Display database tables

•   Create new data

•   Easily update data

•   Safely delete data

•   Automatic form validation

•   Search and filtering

•   Export data to CSV/JSON/XML

•   Authentication (via Devise)

•   User action history
• add the line below to your Gemfile
  gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'



• $ bundle install
• $ rails g rails_admin:install
Rails web api 开发
Rails web api 开发
Rails web api 开发
Cache & Daemon
def index
  @messages = Rails.cache.fetch('all_messages', :expires_in => 30.seconds) do
    Message.all
  end

  respond_to do |format|
    format.json { render json: @messages }
  end
end
Started GET "/api/v2/messages.json" for 127.0.0.1 at 2011-09-15 17:29:53 +0800
  Processing by Api::V2::MessagesController#index as JSON
  Message Load (0.1ms)          SELECT "messages".* FROM "messages"
Completed 200 OK in 46ms (Views: 11.4ms | ActiveRecord: 0.4ms)



Started GET "/api/v2/messages.json" for 127.0.0.1 at 2011-09-15 17:29:58 +0800
  Processing by Api::V2::MessagesController#index as JSON
Completed 200 OK in 7ms (Views: 6.1ms | ActiveRecord: 0.2ms)
•    Production



•        Cache


• Production      memcache
Rocweibo::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Code is not reloaded between requests
  config.cache_classes = true

  ...
  # Use a different cache store in production
  # config.cache_store = :mem_cache_store
  ...
  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify
end
Daemon
how to run your Background Job
     rails runner lib/my_script.rb
puts %(There are #{Message.count} messages
and #{User.count} users in our database.)

count = Reply.delete_all(["body LIKE ?", "%fuck%"])
puts "#{count} replies contains "fuck" got deleted."

count = User.delete_all(
  [
    "created_at < ? AND email_confirmed = ?",
    Time.new - 2.days,
    false
  ]
)

puts "#{count} not confirmed users within 2 days got deleted."
Delayed Job
http://railscasts.com/episodes/171-delayed-job
Rails web api 开发
still interesting...

•   http://martinciu.com/2011/01/mounting-grape-api-inside-rails-
    application.html

•   http://docs.dotcloud.com/services/ruby/

•   http://railscasts.com/episodes/171-delayed-job

•   http://www.sinatrarb.com/
@shaokunwu
http://weibo.com/shaokunwu

More Related Content

KEY
More to RoC weibo
shaokun
 
PDF
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
PPTX
REST APIs in Laravel 101
Samantha Geitz
 
PPTX
Using WordPress as your application stack
Paul Bearne
 
ODP
Javascript laravel's friend
Bart Van Den Brande
 
PDF
Rails 3 Beautiful Code
GreggPollack
 
PDF
Developing apps using Perl
Anatoly Sharifulin
 
PDF
Inside Bokete: Web Application with Mojolicious and others
Yusuke Wada
 
More to RoC weibo
shaokun
 
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
REST APIs in Laravel 101
Samantha Geitz
 
Using WordPress as your application stack
Paul Bearne
 
Javascript laravel's friend
Bart Van Den Brande
 
Rails 3 Beautiful Code
GreggPollack
 
Developing apps using Perl
Anatoly Sharifulin
 
Inside Bokete: Web Application with Mojolicious and others
Yusuke Wada
 

What's hot (20)

PDF
Phinx talk
Michael Peacock
 
PDF
Building web framework with Rack
sickill
 
KEY
Phpne august-2012-symfony-components-friends
Michael Peacock
 
PDF
Rails 3 overview
Yehuda Katz
 
PDF
Getting Started-with-Laravel
Mindfire Solutions
 
PDF
Fabric Python Lib
Simone Federici
 
ODP
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
PPT
Web service with Laravel
Abuzer Firdousi
 
PDF
Rails2 Pr
xibbar
 
PPTX
Express JS
Alok Guha
 
PDF
Introduction to Rails - presented by Arman Ortega
arman o
 
PPTX
From Ruby to Node.js
jubilem
 
PPTX
An introduction to Laravel Passport
Michael Peacock
 
PPTX
Wykorzystanie form request przy implementacji API w Laravelu
Laravel Poland MeetUp
 
PDF
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
PPTX
Service approach for development Rest API in Symfony2
Sumy PHP User Grpoup
 
PPT
Slim RedBeanPHP and Knockout
Vic Metcalfe
 
PDF
RESTful web services
Tudor Constantin
 
PDF
Perl web frameworks
diego_k
 
PDF
Introduction to Node.JS Express
Eueung Mulyana
 
Phinx talk
Michael Peacock
 
Building web framework with Rack
sickill
 
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Rails 3 overview
Yehuda Katz
 
Getting Started-with-Laravel
Mindfire Solutions
 
Fabric Python Lib
Simone Federici
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Web service with Laravel
Abuzer Firdousi
 
Rails2 Pr
xibbar
 
Express JS
Alok Guha
 
Introduction to Rails - presented by Arman Ortega
arman o
 
From Ruby to Node.js
jubilem
 
An introduction to Laravel Passport
Michael Peacock
 
Wykorzystanie form request przy implementacji API w Laravelu
Laravel Poland MeetUp
 
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
Service approach for development Rest API in Symfony2
Sumy PHP User Grpoup
 
Slim RedBeanPHP and Knockout
Vic Metcalfe
 
RESTful web services
Tudor Constantin
 
Perl web frameworks
diego_k
 
Introduction to Node.JS Express
Eueung Mulyana
 
Ad

Viewers also liked (8)

KEY
Rack
shaokun
 
PPT
WebSocket 实时推特流
shaokun
 
KEY
VIM for the PHP Developer
John Congdon
 
PPT
Git flow
shaokun
 
KEY
iOS 图片浏览器 DIY
shaokun
 
PPT
Rest Ruby On Rails
shaokun
 
PPTX
Rails Engine | Modular application
mirrec
 
KEY
Namespace less engine
shaokun
 
Rack
shaokun
 
WebSocket 实时推特流
shaokun
 
VIM for the PHP Developer
John Congdon
 
Git flow
shaokun
 
iOS 图片浏览器 DIY
shaokun
 
Rest Ruby On Rails
shaokun
 
Rails Engine | Modular application
mirrec
 
Namespace less engine
shaokun
 
Ad

Similar to Rails web api 开发 (20)

PPTX
Infrastructure as code: running microservices on AWS using Docker, Terraform,...
Yevgeniy Brikman
 
PDF
Infrastructureascode slideshare-160331143725
miguel dominguez
 
PDF
Infrastructureascode slideshare-160331143725
MortazaJohari
 
KEY
Supa fast Ruby + Rails
Jean-Baptiste Feldis
 
PDF
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
PDF
Cloud Foundry Open Tour China
marklucovsky
 
PDF
Phoenix for Rails Devs
Diacode
 
PPTX
Ruby on Rails and Docker - Why should I care?
Adam Hodowany
 
PPTX
Dev streams2
David Mc Donagh
 
PDF
Cloud Foundry Open Tour China (english)
marklucovsky
 
PDF
Intro to Rack
Rubyc Slides
 
PDF
Making a small QA system with Docker
Naoki AINOYA
 
PPTX
Amazon Web Services and Docker: from developing to production
Paolo latella
 
PDF
From development environments to production deployments with Docker, Compose,...
Jérôme Petazzoni
 
KEY
Wider than rails
Alexey Nayden
 
PPTX
Building RESTful APIs w/ Grape
Daniel Doubrovkine
 
PPTX
Deploying your web application with AWS ElasticBeanstalk
Julien SIMON
 
PDF
A Tale of a Server Architecture (Frozen Rails 2012)
Flowdock
 
PDF
Exploring MySQL Operator for Kubernetes in Python
Ivan Ma
 
PPTX
Control your deployments with Capistrano
Ramazan K
 
Infrastructure as code: running microservices on AWS using Docker, Terraform,...
Yevgeniy Brikman
 
Infrastructureascode slideshare-160331143725
miguel dominguez
 
Infrastructureascode slideshare-160331143725
MortazaJohari
 
Supa fast Ruby + Rails
Jean-Baptiste Feldis
 
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
Cloud Foundry Open Tour China
marklucovsky
 
Phoenix for Rails Devs
Diacode
 
Ruby on Rails and Docker - Why should I care?
Adam Hodowany
 
Dev streams2
David Mc Donagh
 
Cloud Foundry Open Tour China (english)
marklucovsky
 
Intro to Rack
Rubyc Slides
 
Making a small QA system with Docker
Naoki AINOYA
 
Amazon Web Services and Docker: from developing to production
Paolo latella
 
From development environments to production deployments with Docker, Compose,...
Jérôme Petazzoni
 
Wider than rails
Alexey Nayden
 
Building RESTful APIs w/ Grape
Daniel Doubrovkine
 
Deploying your web application with AWS ElasticBeanstalk
Julien SIMON
 
A Tale of a Server Architecture (Frozen Rails 2012)
Flowdock
 
Exploring MySQL Operator for Kubernetes in Python
Ivan Ma
 
Control your deployments with Capistrano
Ramazan K
 

Recently uploaded (20)

PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Software Development Company | KodekX
KodekX
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 

Rails web api 开发

  • 1. Rails: Web API [email protected] Thanks to Leon Du and Rain Chen
  • 2. You should start with... • ruby 1.9.2 Performance, Threads/Fibers, Encoding/Unicode... • rails 3.1.0 Asset pipeline, HTTP streaming, jQuery
  • 7. talk about... • API • API • API • •
  • 8. Start Simple but Elegant http://localhost:3000/api/messages http://localhost:3000/api/messages/{id}
  • 9. $ git clone git://github.com/kudelabs/roc-demo2.git • $ cd roc-demo2 • $ bundle install • $ rake db:create • $ rake db:migrate • $ rails server • goto http://localhost:3000
  • 10. $ rails generate controller api::messages apps/controllers/api/messages_controller.rb test/functional/api/messages_controller_test.rb
  • 11. apps/controllers/api/messages_controller.rb class Api::MessagesController < ApplicationController # GET /api/messages.json def index @messages = Message.all respond_to do |format| format.json { render json: @messages } end end # GET /api/messages/1.json def show @message = Message.find(params[:id]) respond_to do |format| format.json { render json: @message } end end end
  • 13. Start Alone but Test is Your Partner rake test:functionals rake test:units rake test:integration
  • 14. test/functional/api/messages_controller_test.rb class Api::MessagesControllerTest < ActionController::TestCase setup do @message = messages(:one) end test "should get index" do get :index, format: :json assert_response :success assert_not_nil assigns(:messages) end test "should show message" do get :show, format: :json, id: @message.to_param assert_response :success end end
  • 15. API
  • 16. built-in Namespaced controllers http://localhost:3000/api/v2/messages Rocweibo::Application.routes.draw do namespace :api do resources :messages namespace :v2 do resources :messages end end end
  • 17. test/functional/api/v2/messages_controller_test.rb class Api::V2::MessagesController < Api::ApplicationController before_filter :authenticate, :only => :create ... # curl -X POST -H "Accept: application/json" --user [email protected]:a # http://localhost:3000/api/v2/messages -d "message[body]=abcdefg" def create @message = Message.new(params[:message]) @message.user = @current_user @message.save! render json: @message end private def authenticate if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) } @current_user = user else request_http_basic_authentication end end end
  • 18. Keep Refactoring whenever You could Don’t Repeat Yourself & Decoupling
  • 19. class Api::V2::MessagesController < Api::ApplicationController ... private def authenticate if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) } @current_user = user else request_http_basic_authentication end end end class Api::ApplicationController < ActionController::Base private def authenticate if user = authenticate_with_http_basic { |u, p| User.authenticate(u, p) } @current_user = user else request_http_basic_authentication end end end
  • 20. /app/controllers/api/application_controller.rb class Api::ApplicationController < ActionController::Base end /app/controllers/application_controller.rb class ApplicationController < ActionController::Base helper_method :current_user, :logged_in? protect_from_forgery before_filter :require_logged_in ... end
  • 21. Grape A opinionated micro-framework for creating REST-like APIs in Ruby.
  • 22. class Rocweibo::V1::API < Grape::API prefix 'api' version 'v1' resource :messages do get do Message.limit(20) end get ':id' do Message.find(params[:id]) end end end Rocweibo::Application.routes.draw do mount Rocweibo::V1::API => "/" # mount API routes ... end
  • 23. Where to HOST your app?
  • 24. No Easy Way to Host in China :( • Amazon EC2 • Linode • DotCloud • Heroku
  • 25. DotCloud $ dotcloud push {myapp} {myrepopath}/
  • 26. • $ dotcloud create rocdemo • $ touch dotcloud.yml • $ dotcloud push rocdemo . • or $ dotcloud push -b mybranch rocdemo . Deployment finished. Your application is available at the following URLs www: http://rocdemo-limiru2n.dotcloud.com/
  • 27. add mysql service # just update the content of your dotcloud.yml www: type: ruby $ dotcloud info rocdemo data: type: mysql data: config: mysql_password: ... instances: 1 type: mysql # also, update the content of your database.yml www: production: config: adapter: mysql2 rack-env: production encoding: utf8 ruby-version: 1.9.2 reconnect: false instances: 1 database: roc_demo2_production type: ruby pool: 5 url: http://rocdemo-limiru2n.dotclo username: root password: ... port: 14895 host: rocdemo-LIMIRU2N.dotcloud.com
  • 28. • dotcloud logs rocdemo.www • dotcloud ssh rocdemo.www • dotcloud info rocdemo
  • 30. Display database tables • Create new data • Easily update data • Safely delete data • Automatic form validation • Search and filtering • Export data to CSV/JSON/XML • Authentication (via Devise) • User action history
  • 31. • add the line below to your Gemfile gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git' • $ bundle install • $ rails g rails_admin:install
  • 36. def index @messages = Rails.cache.fetch('all_messages', :expires_in => 30.seconds) do Message.all end respond_to do |format| format.json { render json: @messages } end end
  • 37. Started GET "/api/v2/messages.json" for 127.0.0.1 at 2011-09-15 17:29:53 +0800 Processing by Api::V2::MessagesController#index as JSON Message Load (0.1ms) SELECT "messages".* FROM "messages" Completed 200 OK in 46ms (Views: 11.4ms | ActiveRecord: 0.4ms) Started GET "/api/v2/messages.json" for 127.0.0.1 at 2011-09-15 17:29:58 +0800 Processing by Api::V2::MessagesController#index as JSON Completed 200 OK in 7ms (Views: 6.1ms | ActiveRecord: 0.2ms)
  • 38. Production • Cache • Production memcache
  • 39. Rocweibo::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true ... # Use a different cache store in production # config.cache_store = :mem_cache_store ... # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify end
  • 40. Daemon how to run your Background Job rails runner lib/my_script.rb
  • 41. puts %(There are #{Message.count} messages and #{User.count} users in our database.) count = Reply.delete_all(["body LIKE ?", "%fuck%"]) puts "#{count} replies contains "fuck" got deleted." count = User.delete_all( [ "created_at < ? AND email_confirmed = ?", Time.new - 2.days, false ] ) puts "#{count} not confirmed users within 2 days got deleted."
  • 44. still interesting... • http://martinciu.com/2011/01/mounting-grape-api-inside-rails- application.html • http://docs.dotcloud.com/services/ruby/ • http://railscasts.com/episodes/171-delayed-job • http://www.sinatrarb.com/

Editor's Notes