Grape - 拥有REST风格API的Ruby框架

jopen 12年前

Grape是一个拥有类似REST API的Ruby微型框架。它设计运行在Rack或补充现有Web应用框架如Rails或Sinatra,提供一种简单DSL来简化RESTful APIs开发。它已经内置支持一些常见约束,包括multiple formats, subdomain/prefix restriction, content negotiation, versioning等。下面是基本的用法:

class 推ter::API < Grape::API    version 'v1', :using => :header, :vendor => '推ter'    format :json      helpers do      def current_user        @current_user ||= User.authorize!(env)      end        def authenticate!        error!('401 Unauthorized', 401) unless current_user      end    end      resource :statuses do        desc "Return a public timeline."      get :public_timeline do        Status.limit(20)      end        desc "Return a personal timeline."      get :home_timeline do        authenticate!        current_user.statuses.limit(20)      end        desc "Return a status."      params do        requires :id, :type => Integer, :desc => "Status id."      end      get ':id' do        Status.find(params[:id])      end        desc "Create a status."      params do        requires :status, :type => String, :desc => "Your status."      end      post do        authenticate!        Status.create!({          :user => current_user,          :text => params[:status]        })      end        desc "Update a status."      params do        requires :id, :type => String, :desc => "Status ID."        requires :status, :type => String, :desc => "Your status."      end      put ':id' do        authenticate!        current_user.statuses.find(params[:id]).update({          :user => current_user,          :text => params[:status]        })      end        desc "Delete a status."      params do        requires :id, :type => String, :desc => "Status ID."      end      delete ':id' do        authenticate!        current_user.statuses.find(params[:id]).destroy      end      end    end

项目主页:http://www.open-open.com/lib/view/home/1356229655416