Skip to content

Instantly share code, notes, and snippets.

@SauloSilva
Last active August 29, 2015 14:02
Show Gist options
  • Save SauloSilva/bf15c5bbda4aef659dc4 to your computer and use it in GitHub Desktop.
Save SauloSilva/bf15c5bbda4aef659dc4 to your computer and use it in GitHub Desktop.
Hints to api at rails
# config/initializer/inflections.rb => module customize API
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'API'
end
# hints for namespace and subdomains
# api.bar.com/foo/
BarRails::Application.routes.draw do
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :foo
end
end
# curls
# => return header information
$ curl -I http://foo.com.br
# => return content type
$ curl -IH 'Accept: application/json' localhost:3000/foo
# => sent POST format
$ curl -i -X POST -d "foo[bar]=foozin" http://localhost:3000/foo
# => with basic authentication
$ curl -IH 'Accept: application/json' -u 'foo:secret' http://cs-zombies-dev.com:3000/zoombies
$ curl -I -H "Authorization: Token token=a45fb396579a25458d23208560742610" -H 'Accept: application/json' http://cs-zombies-dev.com:3000/zombies
# surving many languages
gem 'http_accept_language'
class ApplicationController < ActionController::Base
#protect_from_forgery with: :exception
protect_from_forgery with: :null_session
before_action :set_locale
protected
def set_locale
I18n.locale = request.headers['Accept-Language']
end
end
# no body return with POST request controller
def create
human = Human.new(human_params)
if human.save
head 204, location: human
else
render json: human.errors, status: 422
end
end
# Authentication
class ApplicationController < ActionController::Base
before_action :authenticate
protected
def authenticate
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token do |token|
User.find_by(auth_token: token)
end
end
def render_unauthorized
self.headers['WWW-Authenticate'] = 'Token realm="Zombies"'
respond_to do |format|
format.json { render json: 'Bad credentials', status: 401 }
format.xml { render xml: 'Bad credentials', status: 401 }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment