Here how we make a web service: (based on Simple web service API with Ruby on Rails)
Create a simple application:
rails new eventsservices
cd eventsservices
rails g scaffold event title:string time:datetime
rake db:migrate
rails s
Open http://localhost:3000/events/, click "New Event" and type in some data.
Interesting part is here: by default, ROR knows how to show data in html JSON:
- # GET /events/1
- # GET /events/1.json
- def show
- @event = Event.find(params[:id])
- respond_to do |format|
- format.html # show.html.erb
- format.json { render json: @event }
- end
- end
Adding xml is easy:
- # GET /events/1
- # GET /events/1.json
- # GET /events/1.xml
- def show
- @event = Event.find(params[:id])
- respond_to do |format|
- format.html # show.html.erb
- format.json { render json: @event }
- format.xml { render xml: @event }
- end
- end
Check it out:
A problem here is that this approach does not work with show fuction (ALL Events) in xml part ("Template is missing")
So, let's use a modern respond_to/respond_with functions:
And here we are. Bingo!
...little bit more on json customization here.
So, let's use a modern respond_to/respond_with functions:
- respond_to :html, :xml, :json
- # GET /events
- # GET /events.json
- # GET /events.xml
- def index
- respond_with(@events = Event.all)
- end
- # GET /events/1
- # GET /events/1.json
- # GET /events/1.xml
- def show
- @event = Event.find(params[:id])
- respond_with(@events = Event.all)
- end
And here we are. Bingo!
...little bit more on json customization here.
No comments:
Post a Comment