Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add api.

  • Loading branch information...
commit 2bb7b71758296e9f12d226edce79437ece099a8b 1 parent 30d1851
@drapergeek authored
View
12 app/controllers/short_urls_controller.rb
@@ -1,4 +1,6 @@
class ShortUrlsController < ApplicationController
+ respond_to :json, :html
+
def new
end
@@ -6,10 +8,16 @@ def create
short_url = ShortUrl.new(url: params[:url], name: params[:name])
if short_url.save
flash[:notice] = "Your url: #{short_url.full_url}"
- redirect_to new_short_url_path
+ respond_to do |format|
+ format.html { redirect_to new_short_url_path }
+ format.json { render json: short_url.to_json }
+ end
else
@errors = short_url.errors
- render :new
+ respond_to do |format|
+ format.html { render :new }
+ format.json { render json: {errors: @errors }, status: :error }
+ end
end
end
View
4 app/models/short_url.rb
@@ -34,6 +34,10 @@ def full_url
"http://#{HOSTNAME}/#{name}"
end
+ def as_json(options = {})
+ { full_url: full_url }.merge(super)
+ end
+
private
def name_must_be_unique
View
26 spec/controllers/short_urls_controller_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+describe ShortUrlsController do
+ describe "#post" do
+ context 'with a valid short url' do
+ it "returns a url" do
+ post :create, url: 'http://google.com', name: 'search', format: :json
+ json = JSON.parse(response.body)
+
+ expect(json["name"]).to eq("search")
+ expect(json["url"]).to eq("http://google.com")
+ expect(json["full_url"]).to eq("http://example.com/search")
+ end
+ end
+
+ context "with an invalid url" do
+ it "returns a json error list" do
+ post :create, url: 'google.com', format: :json
+ json = JSON.parse(response.body)
+
+ expect(response.status).to eq(500)
+ expect(json["errors"]).to include("url")
+ end
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.