Şağıdaki gemleri gemfile dosyamıza ekleyelim
# Rest-Client Dependencies
gem 'mime-types'
gem 'netrc'
gem 'http-cookie'
# rest-client gem
gem 'rest-client'
Projemize veritabanından bağımsız bir model hazırlayalım:
Models/person.rb
class Person
attr_accessor :id, :appellation, :name,:speciality
def initialize(id=nil, appellation=nil, name=nil, speciality=nil)
self.id, self.appellation , self.name, self.speciality= id, appellation, name,speciality
end
end
Controllers/persons_controller.rb dosyasını oluşturup aşağıdaki gibi düzenleyelim
class PersonsController < ActionController::Base
before_action :authenticate_user!
require 'rest-client'
require 'json'
def index
@persons = Array.new
url = "http://localhost:3000/api/v1/person_all.json"
response_data = RestClient.get( url)
if response_data.code == 200
@rdata = JSON.parse(response_data)
else
@rdata = "error"
end
@rdata.each do |person|
@p=Person.new(person["id"],person["appellation"],person["name"],person["speciality"])
@persons.push(@p)
end
end
def show
url = "http://localhost:3000/api/v1/person_show.json"
response_data = RestClient.post( url,:person_id => params[:id] )
@rdata = JSON.parse(response_data)
@person=Person.new( @rdata["id"], @rdata["appellation"], @rdata["name"], @rdata["speciality"])
end
def new
@person = Person.new()
end
def edit
url = "http://localhost:3000/api/v1/person_show.json"
response_data = RestClient.post( url,:person_id => params[:id] )
@rdata = JSON.parse(response_data)
@person=Person.new( @rdata["id"], @rdata["appellation"], @rdata["name"], @rdata["speciality"])
end
def create
@person=params[:person]
url = "http://localhost:3000/api/v1/person_create.json"
response_data = RestClient.post( url,{:appellation => @person[:appellation], :name=>@person[:name], :speciality=>@person[:speciality]})
if response_data=="OK"
redirect_to persons_path
else
render :file => 'public/404.html', :status => :not_found, :layout => false
end
end
def update
@person=params[:person]
url = "http://localhost:3000/api/v1/person_update.json"
response_data = RestClient.put( url,{:person_id => @person[:id],:appellation=>@person[:appellation],:name=>@person[:name],:speciality=>@person[:speciality]} )
if response_data=="OK"
redirect_to persons_path
else
render :file => 'public/404.html', :status => :not_found, :layout => false
end
end
def delete
url = "http://localhost:3000/api/v1/person_destroy.json"
response_data = RestClient.post( url,:person_id => params[:id] )
if response_data=="OK"
redirect_to persons_path
else
render :file => 'public/404.html', :status => :not_found, :layout => false
end
end
end
routes.rb
resources :persons do
get :delete, on: :member
end