Permalink
Browse files

Add api.

  • Loading branch information...
1 parent 30d1851 commit 2bb7b71758296e9f12d226edce79437ece099a8b @drapergeek committed Dec 17, 2012
@@ -1,15 +1,23 @@
class ShortUrlsController < ApplicationController
+ respond_to :json, :html
+
def new
end
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
@@ -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
@@ -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

0 comments on commit 2bb7b71

Please sign in to comment.