How to create a REST API for a Ruby application?

前端 未结 4 1050
臣服心动
臣服心动 2021-01-31 00:47

I would like to know how to provide a Ruby application with a REST API. I could code something based on Ruby\'s TCPServer API, but that seems a bit low-level. Do you think it wo

4条回答
  •  孤街浪徒
    2021-01-31 01:06

    I'm using Sinatra too to develop simple REST solutions.

    The thing is Sinatra is so flexible in many ways. You can build your project structure the way you like more. Usualy we have a lib/ tmp/ and public/ directories and a config.ru and app.rb files but as I sayd you can build whatever you want.

    To remember is that Sinatra is not an usual MVC just because de M (model). For you to use sinatra for Simple CRUD web applications you need simply to load a gem.

    require 'datamapper'

    or other of your choice like sqlite, sequel, ActiveRecord, ...

    and voilá you got a ORM under your Sinatra.

    Under Sinatra you define routes that obey to four main proposes GET, PUT POST and DELETE.

    
    require 'rubygems'
    require 'sinatra'
    
    get '/' do
      erb :home
    end
    
    get '/API/*' do
      api = params[:splat]
      @command_test = api[0]
      @command_helo = api[1]
      #...
      def do_things(with_it)
        #...
      end
      #...
    end
    
    __END__
    
    @@home
    
    helo
    

    well you got the ideia :)

    Finally. Learning Sinatra is not a waste of time because of it simplicity and because it gives (me) foundations of what web programming is. I think In a near future it will be possible to "inject" Sinatra apps (Rack Apps) into a Rails3 project.

    Take a look into github, there you will find many project built with Sinatra. For further reading checkout Sinatra::Base.

提交回复
热议问题