Skip to content

Instantly share code, notes, and snippets.

View GiancarlosIO's full-sized avatar
🔥
Making the web faster!

Giancarlos Isasi GiancarlosIO

🔥
Making the web faster!
View GitHub Profile
# my_api/config/routes.rb
Rails.application.routes.draw do
namespace :api, defaults: { format: "json" } do
namespace :v1 do
resources :users
end
end
end
# my_api/app/models/user.rb
class User < ActiveRecord::Base
validates :email, presence: true, uniqueness: true
validates :name, presence: true
end
# my_api/app/controller/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController
def index
@users = User.all
end
end
# my_api/rspec/requests/users_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::UsersController, type: :request do
describe "GET /users" do
before :each do
FactoryGirl.create_list(:users, 1)
get "/api/v1/users"
# my_api/app/views/api/v1/users/index.json.jbuilder
json.array! @users do |user|
json.(user, :id, :email, :name)
end
class UsersController < ApplicationController
before_action :find_course, only: [:show, :edit, :update, :destroy]
def index
@users = User.all
end
def show
# find_user
describe UsersController do
describe 'GET index' do
before do
@user = FactoryGirl.create(:user)
end
it 'ok' do
get :index
expect(response).to have_http_status(:ok)
# my_api/app/models/user.rb
class User < ActiveRecord::Base
validates :email, presence: true, uniqueness: true
validates :name, presence: true
def self.with_token(data)
User.where(email: data[:email]).first_or_create do |user|
user.email = data[:email]
class Token < ApplicationRecord
belongs_to :user
before_create :generate_token
def valid?
self.expires_at > DateTime.now
end
private
# POST api/v1/users, params: { user: {email: '[email protected]', name: 'Giancarlos Isasi' } }
def create
if params[:user]
@user = User.with_token(params[:user]) # le pasamos la información que nuestro metodo 'with_token' usara para crear al usuario
@token = @user.tokens.create() # Al usuario que nos devuelve nuestro parametro 'with_token' le creamos un nuevo token
render "api/v1/users/show" # en esta vista mostraremos la info del usuario y su token respectivo
else
render json: { error: 'user params info is missing' } # solo si no nos envian la info necesaria
end
end