-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodos-api.rb
101 lines (78 loc) · 1.76 KB
/
todos-api.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
ENV['SECRET_KEY_BASE'] = 'my_secret_key_base'
ENV['DATABASE_URL'] = "sqlite3:///#{Dir.pwd}/todos-api.sqlite"
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem 'uni_rails', '~> 0.5.0'
gem 'sqlite3', '~> 1.7'
end
require 'uni_rails'
require 'sqlite3'
ActiveRecord::Base.establish_connection
ActiveRecord::Schema.define do
create_table :todos, force: :cascade do |t|
t.string :name
t.datetime :completed_at
t.timestamps
end
end
UniRails.routes do
resources :todos do
put :complete, on: :member
end
end
# MODELS
class Todo < ActiveRecord::Base
validates :name, presence: true
def complete(at: Time.zone.now)
update(completed_at: at)
end
end
# CONTROLLERS
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
class TodosController < ApplicationController
before_action :set_todo, only: [:show, :update, :destroy, :complete]
def index
@todos = Todo.all
render json: @todos
end
def show
render json: @todo
end
def create
@todo = Todo.new(todo_params)
if @todo.save
render json: @todo, status: :created, location: @todo
else
render json: @todo.errors, status: :unprocessable_entity
end
end
def update
if @todo.update(todo_params)
render json: @todo
else
render json: @todo.errors, status: :unprocessable_entity
end
end
def complete
if @todo.complete
render json: @todo
else
render json: @todo.errors, status: :unprocessable_entity
end
end
def destroy
@todo.destroy
head :no_content
end
private
def set_todo
@todo = Todo.find(params[:id])
end
def todo_params
params.require(:todo).permit(:name, :status)
end
end
UniRails.run(Port: 3000)