Now I would like to write code example to manage REST in Ruby on Rails that contains four methods like GET, POST, PUT and DELETE.
Please pay attention to look at the code as below:

require 'rubygems'
require 'net/http'
module MyREST
	def self.get(url)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('GET', uri.request_uri)
		resp.body
	end

	def self.post(url, data, content_type)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('POST', uri.request_uri, data, 'Content-Type' => content_type)
	end

	def self.put(url, data, content_type)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('PUT', uri.request_uri, data, 'Content-Type' => content_type)
	end

	def self.delete(url)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('DELETE', uri.request_uri)
	end

end

If you want to use this code inside Rails project, you can edit enviroment.rb under config folder and add this one line code

require ‘myrest’

RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION

require File.join(File.dirname(__FILE__), 'boot')

Rails::Initializer.run do |config|
    require 'myrest'
end

And u call MyREST all over in the Rails project.
Here is an example to call MyREST.

MyREST.put url,contentType

Please enjoy your self

Advertisements