Rails web api 开发

2,079 views

Published on

Get your started for developing Web API through Rails.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,079
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
33
Comments
0
Likes
4
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
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Rails web api 开发

    1. 1. Rails: Web API shaokun.wu@gmail.com Thanks to Leon Du and Rain Chen
    2. 2. You should start with...• ruby 1.9.2 Performance, Threads/Fibers, Encoding/Unicode...• rails 3.1.0 Asset pipeline, HTTP streaming, jQuery
    3. 3. Rails on Campushttps://github.com/kudelabs/roc-demo1https://github.com/kudelabs/roc-demo2
    4. 4. GZRubyhttp://groups.google.com/group/gzruby?lnk=srg
    5. 5. talk about...• API• API• API••
    6. 6. Start Simple but Elegant http://localhost:3000/api/messages http://localhost:3000/api/messages/{id}
    7. 7. • $ 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
    8. 8. • $ rails generate controller api::messages apps/controllers/api/messages_controller.rb test/functional/api/messages_controller_test.rb
    9. 9. 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
    10. 10. curl http://localhost:3000/api/messages
    11. 11. Start Alone butTest is Your Partner rake test:functionals rake test:units rake test:integration
    12. 12. 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
    13. 13. API
    14. 14. 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
    15. 15. test/functional/api/v2/messages_controller_test.rbclass 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 endend
    16. 16. Keep Refactoringwhenever You could Don’t Repeat Yourself & Decoupling
    17. 17. 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 endendclass 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 endend
    18. 18. /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
    19. 19. GrapeA opinionated micro-framework for creating REST-like APIs in Ruby.
    20. 20. 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 endend Rocweibo::Application.routes.draw do mount Rocweibo::V1::API => "/" # mount API routes ... end
    21. 21. Where to HOST your app?
    22. 22. No Easy Way to Host in China :(• Amazon EC2• Linode• DotCloud• Heroku
    23. 23. DotCloud$ dotcloud push {myapp} {myrepopath}/
    24. 24. • $ dotcloud create rocdemo• $ touch dotcloud.yml• $ dotcloud push rocdemo .• or $ dotcloud push -b mybranch rocdemo .Deployment finished. Your application is available at the following URLswww: http://rocdemo-limiru2n.dotcloud.com/
    25. 25. add mysql service# just update the content of your dotcloud.ymlwww: type: ruby $ dotcloud info rocdemodata: 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
    26. 26. • dotcloud logs rocdemo.www• dotcloud ssh rocdemo.www• dotcloud info rocdemo
    27. 27. Rails Admin
    28. 28. • 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
    29. 29. • 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
    30. 30. Cache & Daemon
    31. 31. 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 } endend
    32. 32. 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 JSONCompleted 200 OK in 7ms (Views: 6.1ms | ActiveRecord: 0.2ms)
    33. 33. • Production• Cache• Production memcache
    34. 34. 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 = :notifyend
    35. 35. Daemonhow to run your Background Job rails runner lib/my_script.rb
    36. 36. puts %(There are #{Message.count} messagesand #{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."
    37. 37. Delayed Jobhttp://railscasts.com/episodes/171-delayed-job
    38. 38. 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/
    39. 39. @shaokunwuhttp://weibo.com/shaokunwu

    ×