├── .gitignore ├── Gemfile ├── Gemfile.lock ├── README.md ├── Rakefile ├── app ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── application_controller.rb │ ├── concerns │ │ └── .keep │ ├── posts_controller.rb │ ├── sessions_controller.rb │ └── users_controller.rb ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ ├── post.rb │ └── user.rb ├── serializers │ ├── post_serializer.rb │ ├── session_serializer.rb │ └── user_serializer.rb └── views │ └── layouts │ ├── mailer.html.erb │ └── mailer.text.erb ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── active_model_serializers.rb │ ├── active_record_belongs_to_required_by_default.rb │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── callback_terminator.rb │ ├── cors.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ ├── ssl_options.rb │ ├── to_time_preserves_timezone.rb │ └── wrap_parameters.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb ├── secrets.yml └── spring.rb ├── db ├── migrate │ ├── 20160616072622_create_users.rb │ └── 20160616113032_create_posts.rb ├── schema.rb └── seeds.rb ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public ├── 404.html ├── 422.html ├── 500.html ├── apple-touch-icon-precomposed.png ├── apple-touch-icon.png ├── favicon.ico └── robots.txt ├── test ├── controllers │ ├── .keep │ ├── posts_controller_test.rb │ ├── sessions_controller_test.rb │ ├── sessions_routes_test.rb │ └── users_controller_test.rb ├── fixtures │ ├── .keep │ ├── files │ │ └── .keep │ ├── posts.yml │ └── users.yml ├── integration │ ├── .keep │ └── session_flow_test.rb ├── mailers │ └── .keep ├── models │ └── .keep └── test_helper.rb └── tmp └── .keep /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle 2 | /db/*.sqlite3 3 | /db/*.sqlite3-journal 4 | /log/* 5 | /tmp/* 6 | !/log/.keep 7 | !/tmp/.keep 8 | .byebug_history 9 | .DS_Store 10 | /bin/ -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | 4 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 5 | gem 'rails', '>= 5.0', '< 5.1' 6 | # Use sqlite3 as the database for Active Record 7 | gem 'sqlite3' 8 | # Use Puma as the app server 9 | gem 'puma', '~> 3.0' 10 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 11 | # gem 'jbuilder', '~> 2.0' 12 | # Use Redis adapter to run Action Cable in production 13 | # gem 'redis', '~> 3.0' 14 | # Use ActiveModel has_secure_password 15 | gem 'bcrypt', '~> 3.1.7' 16 | 17 | # Use Capistrano for deployment 18 | # gem 'capistrano-rails', group: :development 19 | 20 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 21 | gem 'rack-cors' 22 | 23 | # Serialization 24 | gem 'active_model_serializers', '~> 0.10.0' 25 | 26 | group :development, :test do 27 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 28 | gem 'byebug', platform: :mri 29 | end 30 | 31 | group :development do 32 | gem 'listen', '~> 3.0.5' 33 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 34 | gem 'spring' 35 | gem 'spring-watcher-listen', '~> 2.0.0' 36 | end 37 | 38 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 39 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 40 | 41 | gem 'will_paginate' -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.0.0) 5 | actionpack (= 5.0.0) 6 | nio4r (~> 1.2) 7 | websocket-driver (~> 0.6.1) 8 | actionmailer (5.0.0) 9 | actionpack (= 5.0.0) 10 | actionview (= 5.0.0) 11 | activejob (= 5.0.0) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.0.0) 15 | actionview (= 5.0.0) 16 | activesupport (= 5.0.0) 17 | rack (~> 2.0) 18 | rack-test (~> 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.0.0) 22 | activesupport (= 5.0.0) 23 | builder (~> 3.1) 24 | erubis (~> 2.7.0) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 27 | active_model_serializers (0.10.1) 28 | actionpack (>= 4.1, < 6) 29 | activemodel (>= 4.1, < 6) 30 | jsonapi (~> 0.1.1.beta2) 31 | railties (>= 4.1, < 6) 32 | activejob (5.0.0) 33 | activesupport (= 5.0.0) 34 | globalid (>= 0.3.6) 35 | activemodel (5.0.0) 36 | activesupport (= 5.0.0) 37 | activerecord (5.0.0) 38 | activemodel (= 5.0.0) 39 | activesupport (= 5.0.0) 40 | arel (~> 7.0) 41 | activesupport (5.0.0) 42 | concurrent-ruby (~> 1.0, >= 1.0.2) 43 | i18n (~> 0.7) 44 | minitest (~> 5.1) 45 | tzinfo (~> 1.1) 46 | arel (7.0.0) 47 | bcrypt (3.1.11) 48 | builder (3.2.2) 49 | byebug (9.0.5) 50 | concurrent-ruby (1.0.2) 51 | erubis (2.7.0) 52 | ffi (1.9.10) 53 | globalid (0.3.6) 54 | activesupport (>= 4.1.0) 55 | i18n (0.7.0) 56 | json (1.8.3) 57 | jsonapi (0.1.1.beta2) 58 | json (~> 1.8) 59 | listen (3.0.8) 60 | rb-fsevent (~> 0.9, >= 0.9.4) 61 | rb-inotify (~> 0.9, >= 0.9.7) 62 | loofah (2.0.3) 63 | nokogiri (>= 1.5.9) 64 | mail (2.6.4) 65 | mime-types (>= 1.16, < 4) 66 | method_source (0.8.2) 67 | mime-types (3.1) 68 | mime-types-data (~> 3.2015) 69 | mime-types-data (3.2016.0521) 70 | mini_portile2 (2.1.0) 71 | minitest (5.9.0) 72 | nio4r (1.2.1) 73 | nokogiri (1.6.8) 74 | mini_portile2 (~> 2.1.0) 75 | pkg-config (~> 1.1.7) 76 | pkg-config (1.1.7) 77 | puma (3.4.0) 78 | rack (2.0.1) 79 | rack-cors (0.4.0) 80 | rack-test (0.6.3) 81 | rack (>= 1.0) 82 | rails (5.0.0) 83 | actioncable (= 5.0.0) 84 | actionmailer (= 5.0.0) 85 | actionpack (= 5.0.0) 86 | actionview (= 5.0.0) 87 | activejob (= 5.0.0) 88 | activemodel (= 5.0.0) 89 | activerecord (= 5.0.0) 90 | activesupport (= 5.0.0) 91 | bundler (>= 1.3.0, < 2.0) 92 | railties (= 5.0.0) 93 | sprockets-rails (>= 2.0.0) 94 | rails-dom-testing (2.0.1) 95 | activesupport (>= 4.2.0, < 6.0) 96 | nokogiri (~> 1.6.0) 97 | rails-html-sanitizer (1.0.3) 98 | loofah (~> 2.0) 99 | railties (5.0.0) 100 | actionpack (= 5.0.0) 101 | activesupport (= 5.0.0) 102 | method_source 103 | rake (>= 0.8.7) 104 | thor (>= 0.18.1, < 2.0) 105 | rake (11.2.2) 106 | rb-fsevent (0.9.7) 107 | rb-inotify (0.9.7) 108 | ffi (>= 0.5.0) 109 | spring (1.7.2) 110 | spring-watcher-listen (2.0.0) 111 | listen (>= 2.7, < 4.0) 112 | spring (~> 1.2) 113 | sprockets (3.6.3) 114 | concurrent-ruby (~> 1.0) 115 | rack (> 1, < 3) 116 | sprockets-rails (3.1.1) 117 | actionpack (>= 4.0) 118 | activesupport (>= 4.0) 119 | sprockets (>= 3.0.0) 120 | sqlite3 (1.3.11) 121 | thor (0.19.1) 122 | thread_safe (0.3.5) 123 | tzinfo (1.2.2) 124 | thread_safe (~> 0.1) 125 | websocket-driver (0.6.4) 126 | websocket-extensions (>= 0.1.0) 127 | websocket-extensions (0.1.2) 128 | will_paginate (3.1.0) 129 | 130 | PLATFORMS 131 | ruby 132 | 133 | DEPENDENCIES 134 | active_model_serializers (~> 0.10.0) 135 | bcrypt (~> 3.1.7) 136 | byebug 137 | listen (~> 3.0.5) 138 | puma (~> 3.0) 139 | rack-cors 140 | rails (>= 5.0, < 5.1) 141 | spring 142 | spring-watcher-listen (~> 2.0.0) 143 | sqlite3 144 | tzinfo-data 145 | will_paginate 146 | 147 | BUNDLED WITH 148 | 1.12.5 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rails 5 JSON:API demo app 2 | 3 | This is demo application from my [Creating Rails 5 API only application following JSON:API specification](https://www.simplify.ba/articles/2016/06/18/creating-rails5-api-only-application-following-jsonapi-specification/) article. -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. 2 | module ApplicationCable 3 | class Channel < ActionCable::Channel::Base 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. 2 | module ApplicationCable 3 | class Connection < ActionCable::Connection::Base 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | class ApplicationController < ActionController::API 3 | before_action :check_header 4 | before_action :validate_login 5 | 6 | private 7 | def check_header 8 | if ['POST','PUT','PATCH'].include? request.method 9 | if request.content_type != "application/vnd.api+json" 10 | head 406 and return 11 | end 12 | end 13 | end 14 | 15 | def validate_type 16 | if params['data'] && params['data']['type'] 17 | if params['data']['type'] == params[:controller] 18 | return true 19 | end 20 | end 21 | head 409 and return 22 | end 23 | 24 | def validate_login 25 | token = request.headers["X-Api-Key"] 26 | return unless token 27 | user = User.find_by token: token 28 | return unless user 29 | if 15.minutes.ago < user.updated_at 30 | user.touch 31 | @current_user = user 32 | end 33 | end 34 | 35 | def validate_user 36 | head 403 and return unless @current_user 37 | end 38 | 39 | def render_error(resource, status) 40 | render json: resource, status: status, adapter: :json_api, serializer: ActiveModel::Serializer::ErrorSerializer, meta: default_meta 41 | end 42 | 43 | def default_meta 44 | { 45 | licence: 'CC-0', 46 | authors: ['Saša'], 47 | logged_in: (@current_user ? true : false) 48 | } 49 | end 50 | 51 | def pagination_meta(object) 52 | { 53 | current_page: object.current_page, 54 | next_page: object.next_page, 55 | prev_page: object.previous_page, 56 | total_pages: object.total_pages, 57 | total_count: object.total_entries 58 | } 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class PostsController < ApplicationController 2 | before_action :set_post, only: [:show, :update, :destroy] 3 | before_action :validate_user, only: [:create, :update, :destroy] 4 | before_action :validate_type, only: [:create, :update] 5 | 6 | def index 7 | posts = Post.all 8 | if params[:filter] 9 | posts = posts.where(["category = ?", params[:filter]]) 10 | end 11 | if params['sort'] 12 | f = params['sort'].split(',').first 13 | field = f[0] == '-' ? f[1..-1] : f 14 | order = f[0] == '-' ? 'DESC' : 'ASC' 15 | if Post.new.has_attribute?(field) 16 | posts = posts.order("#{field} #{order}") 17 | end 18 | end 19 | posts = posts.page(params[:page] ? params[:page][:number] : 1) 20 | render json: posts, meta: pagination_meta(posts).merge(default_meta), include: ['user'] 21 | end 22 | 23 | def show 24 | render json: @post, meta: default_meta 25 | end 26 | 27 | def create 28 | post = Post.new(post_params) 29 | if post.save 30 | render json: post, status: :created, meta: default_meta 31 | else 32 | render_error(post, :unprocessable_entity) 33 | end 34 | end 35 | 36 | def update 37 | if @post.update_attributes(post_params) 38 | render json: @post, status: :ok, meta: default_meta 39 | else 40 | render_error(@post, :unprocessable_entity) 41 | end 42 | end 43 | 44 | def destroy 45 | @post.destroy 46 | head 204 47 | end 48 | 49 | private 50 | def set_post 51 | begin 52 | @post = Post.find params[:id] 53 | rescue ActiveRecord::RecordNotFound 54 | post = Post.new 55 | post.errors.add(:id, "Wrong ID provided") 56 | render_error(post, 404) and return 57 | end 58 | end 59 | 60 | def post_params 61 | ActiveModelSerializers::Deserialization.jsonapi_parse(params) 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /app/controllers/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | class SessionsController < ApplicationController 2 | def create 3 | data = ActiveModelSerializers::Deserialization.jsonapi_parse(params) 4 | Rails.logger.error params.to_yaml 5 | user = User.where(full_name: data[:full_name]).first 6 | head 406 and return unless user 7 | if user.authenticate(data[:password]) 8 | user.regenerate_token 9 | @current_user = user 10 | render json: user, status: :created, meta: default_meta, serializer: ActiveModel::Serializer::SessionSerializer and return 11 | end 12 | head 403 13 | end 14 | 15 | def destroy 16 | user = User.where(token: params[:id]).first 17 | head 404 and return unless user 18 | user.regenerate_token 19 | head 204 20 | end 21 | end -------------------------------------------------------------------------------- /app/controllers/users_controller.rb: -------------------------------------------------------------------------------- 1 | class UsersController < ApplicationController 2 | before_action :set_user, only: [:show, :update, :destroy] 3 | before_action :validate_user, only: [:create, :update, :destroy] 4 | before_action :validate_type, only: [:create, :update] 5 | 6 | def index 7 | users = User.all 8 | render json: users, meta: default_meta 9 | end 10 | 11 | def show 12 | render json: @user, meta: default_meta 13 | end 14 | 15 | def create 16 | user = User.new(user_params) 17 | if user.save 18 | render json: user, status: :created, meta: default_meta 19 | else 20 | render_error(user, :unprocessable_entity) 21 | end 22 | end 23 | 24 | def update 25 | if @user.update_attributes(user_params) 26 | render json: @user, status: :ok, meta: default_meta 27 | else 28 | render_error(@user, :unprocessable_entity) 29 | end 30 | end 31 | 32 | def destroy 33 | @user.destroy 34 | head 204 35 | end 36 | 37 | private 38 | 39 | def set_user 40 | begin 41 | @user = User.find params[:id] 42 | rescue ActiveRecord::RecordNotFound 43 | user = User.new 44 | user.errors.add(:id, "Wrong ID provided") 45 | render_error(user, 404) and return 46 | end 47 | end 48 | 49 | def user_params 50 | ActiveModelSerializers::Deserialization.jsonapi_parse(params) 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/post.rb: -------------------------------------------------------------------------------- 1 | class Post < ApplicationRecord 2 | belongs_to :user 3 | self.per_page = 50 4 | 5 | validates_presence_of :title, :content, :category, :rating 6 | 7 | end -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | has_secure_token 3 | has_secure_password 4 | has_many :posts, dependent: :destroy 5 | 6 | validates :full_name, presence: true 7 | end -------------------------------------------------------------------------------- /app/serializers/post_serializer.rb: -------------------------------------------------------------------------------- 1 | class PostSerializer < ActiveModel::Serializer 2 | attributes :id, :title, :content, :category, :rating, :created_at, :updated_at 3 | belongs_to :user 4 | link(:self) { post_url(object) } 5 | end -------------------------------------------------------------------------------- /app/serializers/session_serializer.rb: -------------------------------------------------------------------------------- 1 | class SessionSerializer < ActiveModel::Serializer 2 | attributes :id, :full_name, :token 3 | end -------------------------------------------------------------------------------- /app/serializers/user_serializer.rb: -------------------------------------------------------------------------------- 1 | class UserSerializer < ActiveModel::Serializer 2 | attributes :id, :full_name, :description, :created_at 3 | has_many :posts 4 | link(:self) { user_url(object) } 5 | end -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | require "action_controller/railtie" 9 | require "action_mailer/railtie" 10 | require "action_view/railtie" 11 | require "action_cable/engine" 12 | # require "sprockets/railtie" 13 | require "rails/test_unit/railtie" 14 | 15 | # Require the gems listed in Gemfile, including any gems 16 | # you've limited to :test, :development, or :production. 17 | Bundler.require(*Rails.groups) 18 | 19 | module Rails5JsonApiDemo 20 | class Application < Rails::Application 21 | # Settings in config/environments/* take precedence over those specified here. 22 | # Application configuration should go into files in config/initializers 23 | # -- all .rb files in that directory are automatically loaded. 24 | 25 | # Only loads a smaller set of middleware suitable for API only apps. 26 | # Middleware like session, flash, cookies can be added back manually. 27 | # Skip views, helpers and assets when generating a new resource. 28 | config.api_only = true 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | # Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. 2 | production: 3 | adapter: redis 4 | url: redis://localhost:6379/1 5 | 6 | development: 7 | adapter: async 8 | 9 | test: 10 | adapter: async 11 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | if Rails.root.join('tmp/caching-dev.txt').exist? 17 | config.action_controller.perform_caching = true 18 | 19 | config.cache_store = :memory_store 20 | config.public_file_server.headers = { 21 | 'Cache-Control' => 'public, max-age=172800' 22 | } 23 | else 24 | config.action_controller.perform_caching = false 25 | 26 | config.cache_store = :null_store 27 | end 28 | 29 | # Don't care if the mailer can't send. 30 | config.action_mailer.raise_delivery_errors = false 31 | 32 | config.action_mailer.perform_caching = false 33 | 34 | # Print deprecation notices to the Rails logger. 35 | config.active_support.deprecation = :log 36 | 37 | # Raise an error on page load if there are pending migrations. 38 | config.active_record.migration_error = :page_load 39 | 40 | 41 | # Raises error for missing translations 42 | # config.action_view.raise_on_missing_translations = true 43 | 44 | # Use an evented file watcher to asynchronously detect changes in source code, 45 | # routes, locales, etc. This feature depends on the listen gem. 46 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 47 | end 48 | 49 | 50 | Rails.application.routes.default_url_options = { 51 | host: 'localhost', 52 | port: 3000 53 | } -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Disable serving static files from the `/public` folder by default since 18 | # Apache or NGINX already handles this. 19 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 20 | 21 | 22 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 23 | # config.action_controller.asset_host = 'http://assets.example.com' 24 | 25 | # Specifies the header that your server uses for sending files. 26 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 27 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 28 | 29 | # Action Cable endpoint configuration 30 | # config.action_cable.url = 'wss://example.com/cable' 31 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 32 | 33 | # Don't mount Action Cable in the main server process. 34 | # config.action_cable.mount_path = nil 35 | 36 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 37 | # config.force_ssl = true 38 | 39 | # Use the lowest log level to ensure availability of diagnostic information 40 | # when problems arise. 41 | config.log_level = :debug 42 | 43 | # Prepend all log lines with the following tags. 44 | config.log_tags = [ :request_id ] 45 | 46 | # Use a different cache store in production. 47 | # config.cache_store = :mem_cache_store 48 | 49 | # Use a real queuing backend for Active Job (and separate queues per environment) 50 | # config.active_job.queue_adapter = :resque 51 | # config.active_job.queue_name_prefix = "rails5_json_api_demo_#{Rails.env}" 52 | config.action_mailer.perform_caching = false 53 | 54 | # Ignore bad email addresses and do not raise email delivery errors. 55 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 56 | # config.action_mailer.raise_delivery_errors = false 57 | 58 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 59 | # the I18n.default_locale when a translation cannot be found). 60 | config.i18n.fallbacks = true 61 | 62 | # Send deprecation notices to registered listeners. 63 | config.active_support.deprecation = :notify 64 | 65 | # Use default logging formatter so that PID and timestamp are not suppressed. 66 | config.log_formatter = ::Logger::Formatter.new 67 | 68 | # Use a different logger for distributed setups. 69 | # require 'syslog/logger' 70 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 71 | 72 | if ENV["RAILS_LOG_TO_STDOUT"].present? 73 | logger = ActiveSupport::Logger.new(STDOUT) 74 | logger.formatter = config.log_formatter 75 | config.logger = ActiveSupport::TaggedLogging.new(logger) 76 | end 77 | 78 | # Do not dump schema after migrations. 79 | config.active_record.dump_schema_after_migration = false 80 | end 81 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => 'public, max-age=3600' 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | config.action_mailer.perform_caching = false 31 | 32 | # Tell Action Mailer not to deliver emails to the real world. 33 | # The :test delivery method accumulates sent emails in the 34 | # ActionMailer::Base.deliveries array. 35 | config.action_mailer.delivery_method = :test 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | 44 | Rails.application.routes.default_url_options = { 45 | host: 'localhost', 46 | port: 3000 47 | } -------------------------------------------------------------------------------- /config/initializers/active_model_serializers.rb: -------------------------------------------------------------------------------- 1 | ActiveModel::Serializer.config.adapter = :json_api -------------------------------------------------------------------------------- /config/initializers/active_record_belongs_to_required_by_default.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Require `belongs_to` associations by default. This is a new Rails 5.0 4 | # default, so it is introduced as a configuration option to ensure that apps 5 | # made on earlier versions of Rails are not affected when upgrading. 6 | Rails.application.config.active_record.belongs_to_required_by_default = true 7 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ApplicationController.renderer.defaults.merge!( 4 | # http_host: 'example.org', 5 | # https: false 6 | # ) 7 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /config/initializers/callback_terminator.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Do not halt callback chains when a callback returns false. This is a new 4 | # Rails 5.0 default, so it is introduced as a configuration option to ensure 5 | # that apps made with earlier versions of Rails are not affected when upgrading. 6 | ActiveSupport.halt_callback_chains_on_return_false = false 7 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Avoid CORS issues when API is called from the frontend app. 4 | # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. 5 | 6 | # Read more: https://github.com/cyu/rack-cors 7 | 8 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 9 | allow do 10 | origins '*' 11 | resource '*', 12 | headers: :any, 13 | methods: [:get, :post, :put, :patch, :delete, :options, :head] 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | 6 | Mime::Type.register "application/vnd.api+json", :json -------------------------------------------------------------------------------- /config/initializers/ssl_options.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure SSL options to enable HSTS with subdomains. 4 | Rails.application.config.ssl_options = { hsts: { subdomains: true } } 5 | -------------------------------------------------------------------------------- /config/initializers/to_time_preserves_timezone.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Preserve the timezone of the receiver when calling to `to_time`. 4 | # Ruby 2.4 will change the behavior of `to_time` to preserve the timezone 5 | # when converting to an instance of `Time` instead of the previous behavior 6 | # of converting to the local system timezone. 7 | # 8 | # Rails 5.0 introduced this config option so that apps made with earlier 9 | # versions of Rails are not affected when upgrading. 10 | ActiveSupport.to_time_preserves_timezone = true 11 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum, this matches the default thread size of Active Record. 6 | # 7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests, default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. If you use this option 30 | # you need to make sure to reconnect any threads in the `on_worker_boot` 31 | # block. 32 | # 33 | # preload_app! 34 | 35 | # The code in the `on_worker_boot` will be called if you are using 36 | # clustered mode by specifying a number of `workers`. After each worker 37 | # process is booted this block will be run, if you are using `preload_app!` 38 | # option you will want to use this block to reconnect to any threads 39 | # or connections that may have been created at application boot, Ruby 40 | # cannot share connections between processes. 41 | # 42 | # on_worker_boot do 43 | # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) 44 | # end 45 | 46 | # Allow puma to be restarted by `rails restart` command. 47 | plugin :tmp_restart 48 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | resources :users 3 | resources :posts 4 | 5 | post 'sessions' => 'sessions#create' 6 | delete 'sessions/:id' => 'sessions#destroy' 7 | end 8 | -------------------------------------------------------------------------------- /config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rails secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: 03aad1c01f622b06f7afea09e7f8c98311e68657477ad4b165708693a5321601ca9d75dd68e50bd48c0cc544064c262ab4690b73bd5227116b1a966a11dad6de 15 | 16 | test: 17 | secret_key_base: effbbfa80a4bcc7af07086fa0986173434ae13b8e154e76e020150108374ca997205b0a3ae402d6b854cd22ee56742a212d8a93a5e940942e0eeb85b502556ae 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w( 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ).each { |path| Spring.watch(path) } 7 | -------------------------------------------------------------------------------- /db/migrate/20160616072622_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[5.0] 2 | def change 3 | create_table :users do |t| 4 | t.timestamps 5 | t.string :full_name 6 | t.string :password_digest 7 | t.string :token 8 | t.text :description 9 | end 10 | add_index :users, :token, unique: true 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20160616113032_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration[5.0] 2 | def change 3 | create_table :posts do |t| 4 | t.timestamps 5 | t.string :title 6 | t.text :content 7 | t.integer :user_id 8 | t.string :category 9 | t.integer :rating 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20160616113032) do 15 | 16 | create_table "posts", force: :cascade do |t| 17 | t.datetime "created_at", null: false 18 | t.datetime "updated_at", null: false 19 | t.string "title" 20 | t.text "content" 21 | t.integer "user_id" 22 | t.string "category" 23 | t.integer "rating" 24 | end 25 | 26 | create_table "users", force: :cascade do |t| 27 | t.datetime "created_at", null: false 28 | t.datetime "updated_at", null: false 29 | t.string "full_name" 30 | t.string "password_digest" 31 | t.string "token" 32 | t.text "description" 33 | t.index ["token"], name: "index_users_on_token", unique: true 34 | end 35 | 36 | end 37 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/log/.keep -------------------------------------------------------------------------------- /public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/controllers/.keep -------------------------------------------------------------------------------- /test/controllers/posts_controller_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | require 'json' 3 | 4 | class PostsControllerTest < ActionController::TestCase 5 | 6 | test "Should get valid list of posts" do 7 | get :index, params: { page: { number: 2 } } 8 | assert_response :success 9 | jdata = JSON.parse response.body 10 | assert_equal Post.per_page, jdata['data'].length 11 | assert_equal jdata['data'][0]['type'], 'posts' 12 | l = jdata['links'] 13 | assert_equal l['first'], l['prev'] 14 | assert_equal l['last'], l['next'] 15 | assert_equal Post.count, jdata['meta']['total-count'] 16 | assert_equal 'CC-0', jdata['meta']['licence'] 17 | end 18 | 19 | test "Should get properly sorted list" do 20 | post = Post.order('rating DESC').first 21 | get :index, params: { sort: '-rating' } 22 | assert_response :success 23 | jdata = JSON.parse response.body 24 | assert_equal post.title, jdata['data'][0]['attributes']['title'] 25 | end 26 | 27 | test "Should get filtered list" do 28 | get :index, params: { filter: 'First' } 29 | assert_response :success 30 | jdata = JSON.parse response.body 31 | assert_equal Post.where(category: 'First').count, jdata['data'].length 32 | end 33 | 34 | test "Should get valid post data" do 35 | post = posts('article_0_0') 36 | get :show, params: { id: post.id } 37 | assert_response :success 38 | jdata = JSON.parse response.body 39 | assert_equal post.id.to_s, jdata['data']['id'] 40 | assert_equal post.title, jdata['data']['attributes']['title'] 41 | assert_equal post_url(post, { host: "localhost", port: 3000 }), jdata['data']['links']['self'] 42 | end 43 | 44 | test "Should get JSON:API error block when requesting post data with invalid ID" do 45 | get :show, params: { id: "z" } 46 | assert_response 404 47 | jdata = JSON.parse response.body 48 | assert_equal "Wrong ID provided", jdata['errors'][0]['detail'] 49 | assert_equal '/data/attributes/id', jdata['errors'][0]['source']['pointer'] 50 | end 51 | 52 | test "Creating new post with valid data should create new post" do 53 | user = users('user_1') 54 | @request.headers["Content-Type"] = 'application/vnd.api+json' 55 | @request.headers["X-Api-Key"] = user.token 56 | post :create, params: { data: { type: 'posts', attributes: { title: 'New Title', 57 | content: "New content", 58 | rating: '8', 59 | category: 'Testing2', 60 | user_id: user.id }}} 61 | assert_response 201 62 | jdata = JSON.parse response.body 63 | assert_equal 'New Title', jdata['data']['attributes']['title'] 64 | end 65 | 66 | test "Updating an existing post with valid data should update that post" do 67 | post = posts('article_0_0') 68 | user = users('user_1') 69 | @request.headers["Content-Type"] = 'application/vnd.api+json' 70 | @request.headers["X-Api-Key"] = user.token 71 | patch :update, params: { 72 | id: post.id, 73 | data: { 74 | id: post.id, 75 | type: 'posts', 76 | attributes: { 77 | title: 'New Title' }}} 78 | assert_response 200 79 | jdata = JSON.parse response.body 80 | assert_equal 'New Title', jdata['data']['attributes']['title'] 81 | end 82 | 83 | test "Should delete post" do 84 | user = users('user_1') 85 | pcount = Post.count - 1 86 | @request.headers["X-Api-Key"] = user.token 87 | delete :destroy, params: { id: posts('article_5_24').id } 88 | assert_response 204 89 | assert_equal pcount, Post.count 90 | end 91 | 92 | end -------------------------------------------------------------------------------- /test/controllers/sessions_controller_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | require 'json' 3 | 4 | class SessionsControllerTest < ActionController::TestCase 5 | 6 | test "Creating new session with valid data should create new session" do 7 | user = users('user_0') 8 | @request.headers["Content-Type"] = 'application/vnd.api+json' 9 | post :create, params: { data: { type: 'sessions', attributes: { full_name: user.full_name, 10 | password: 'password' }}} 11 | assert_response 201 12 | jdata = JSON.parse response.body 13 | refute_equal user.token, jdata['data']['attributes']['token'] 14 | end 15 | 16 | test "Should delete session" do 17 | user = users('user_0') 18 | delete :destroy, params: { id: user.token } 19 | assert_response 204 20 | end 21 | end -------------------------------------------------------------------------------- /test/controllers/sessions_routes_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class SessionsRoutesTest < ActionController::TestCase 4 | test "should route to create session" do 5 | assert_routing({ method: 'post', path: '/sessions' }, { controller: "sessions", action: "create" }) 6 | end 7 | test "should route to delete session" do 8 | assert_routing({ method: 'delete', path: '/sessions/something'}, { controller: "sessions", action: "destroy", id: "something" }) 9 | end 10 | end -------------------------------------------------------------------------------- /test/controllers/users_controller_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | require 'json' 3 | 4 | class UsersControllerTest < ActionController::TestCase 5 | 6 | test "Should get valid list of users" do 7 | get :index 8 | assert_response :success 9 | assert_equal response.content_type, 'application/vnd.api+json' 10 | jdata = JSON.parse response.body 11 | assert_equal 6, jdata['data'].length 12 | assert_equal jdata['data'][0]['type'], 'users' 13 | assert_equal 'CC-0', jdata['meta']['licence'] 14 | end 15 | 16 | test "Should get valid user data" do 17 | user = users('user_1') 18 | get :show, params: { id: user.id } 19 | assert_response :success 20 | jdata = JSON.parse response.body 21 | assert_equal user.id.to_s, jdata['data']['id'] 22 | assert_equal user.full_name, jdata['data']['attributes']['full-name'] 23 | assert_equal user_url(user, { host: "localhost", port: 3000 }), jdata['data']['links']['self'] 24 | end 25 | 26 | test "Should get JSON:API error block when requesting user data with invalid ID" do 27 | get :show, params: { id: "z" } 28 | assert_response 404 29 | jdata = JSON.parse response.body 30 | assert_equal "Wrong ID provided", jdata['errors'][0]['detail'] 31 | assert_equal '/data/attributes/id', jdata['errors'][0]['source']['pointer'] 32 | end 33 | 34 | test "Creating new user without sending correct content-type should result in error" do 35 | post :create, params: {} 36 | assert_response 406 37 | end 38 | 39 | test "Creating new user without sending X-Api-Key should result in error" do 40 | @request.headers["Content-Type"] = 'application/vnd.api+json' 41 | post :create, params: {} 42 | assert_response 403 43 | end 44 | 45 | test "Creating new user with incorrect X-Api-Key should result in error" do 46 | @request.headers["Content-Type"] = 'application/vnd.api+json' 47 | @request.headers["X-Api-Key"] = '0000' 48 | post :create, params: {} 49 | assert_response 403 50 | end 51 | 52 | test "Creating new user with invalid type in JSON data should result in error" do 53 | user = users('user_1') 54 | @request.headers["Content-Type"] = 'application/vnd.api+json' 55 | @request.headers["X-Api-Key"] = user.token 56 | post :create, params: { data: { type: 'posts' }} 57 | assert_response 409 58 | end 59 | 60 | test "Creating new user with invalid data should result in error" do 61 | user = users('user_1') 62 | @request.headers["Content-Type"] = 'application/vnd.api+json' 63 | @request.headers["X-Api-Key"] = user.token 64 | post :create, params: { data: { type: 'users', attributes: { full_name: nil, password: nil, password_confirmation: nil }}} 65 | assert_response 422 66 | jdata = JSON.parse response.body 67 | pointers = jdata['errors'].collect { |e| e['source']['pointer'].split('/').last }.sort 68 | assert_equal ['full-name','password'], pointers 69 | end 70 | 71 | test "Creating new user with valid data should create new user" do 72 | user = users('user_1') 73 | @request.headers["Content-Type"] = 'application/vnd.api+json' 74 | @request.headers["X-Api-Key"] = user.token 75 | post :create, params: { data: { type: 'users', attributes: { full_name: 'User Number7', 76 | password: 'password', 77 | password_confirmation: 'password' }}} 78 | assert_response 201 79 | jdata = JSON.parse response.body 80 | assert_equal 'User Number7', jdata['data']['attributes']['full-name'] 81 | end 82 | 83 | test "Updating an existing user with valid data should update that user" do 84 | user = users('user_1') 85 | @request.headers["Content-Type"] = 'application/vnd.api+json' 86 | @request.headers["X-Api-Key"] = user.token 87 | patch :update, params: { id: user.id, data: { id: user.id, 88 | type: 'users', 89 | attributes: { full_name: 'User Number1a' }}} 90 | assert_response 200 91 | jdata = JSON.parse response.body 92 | assert_equal 'User Number1a', jdata['data']['attributes']['full-name'] 93 | end 94 | 95 | test "Should delete user" do 96 | user = users('user_1') 97 | ucount = User.count - 1 98 | @request.headers["X-Api-Key"] = user.token 99 | delete :destroy, params: { id: users('user_5').id } 100 | assert_response 204 101 | assert_equal ucount, User.count 102 | end 103 | end -------------------------------------------------------------------------------- /test/fixtures/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/fixtures/.keep -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/fixtures/posts.yml: -------------------------------------------------------------------------------- 1 | <% 6.times do |i| %> 2 | <% 25.times do |n| %> 3 | article_<%= i %>_<%= n %>: 4 | title: <%= "Example title #{i}/#{n}" %> 5 | content: <%= "Example content #{i}/#{n}" %> 6 | user: <%= "user_#{i}" %> 7 | rating: <%= 1 + i + rand(3) %> 8 | category: <%= i == 0 ? 'First' : 'Example' %> 9 | <% end %><% end %> 10 | -------------------------------------------------------------------------------- /test/fixtures/users.yml: -------------------------------------------------------------------------------- 1 | <% 6.times do |i| %> 2 | user_<%= i %>: 3 | full_name: <%= "User Nr#{i}" %> 4 | password_digest: <%= BCrypt::Password.create('password') %> 5 | token: <%= SecureRandom.base58(24) %> 6 | updated_at: <%= i == 5 ? 1.hour.ago : Time.now %> 7 | <% end %> 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/integration/.keep -------------------------------------------------------------------------------- /test/integration/session_flow_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | require 'json' 3 | 4 | class SessionFlowTestTest < ActionDispatch::IntegrationTest 5 | test "login timeout and meta/logged-in key test" do 6 | user = users('user_5') 7 | # Not logged in, because of timeout 8 | get '/users', params: nil, 9 | headers: { 'X-Api-Key' => user.token } 10 | assert_response :success 11 | jdata = JSON.parse response.body 12 | assert_equal false, jdata['meta']['logged-in'] 13 | # Log in 14 | post '/sessions', 15 | params: { 16 | data: { 17 | type: 'sessions', 18 | attributes: { 19 | full_name: user.full_name, 20 | password: 'password' }}}.to_json, 21 | headers: { 'Content-Type' => 'application/vnd.api+json' } 22 | assert_response 201 23 | jdata = JSON.parse response.body 24 | token = jdata['data']['attributes']['token'] 25 | refute_equal user.token, token 26 | # Logged in 27 | get '/users', params: nil, 28 | headers: { 'X-Api-Key' => token } 29 | assert_response :success 30 | jdata = JSON.parse response.body 31 | assert_equal true, jdata['meta']['logged-in'] 32 | end 33 | end -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/test/models/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require File.expand_path('../../config/environment', __FILE__) 3 | require 'rails/test_help' 4 | 5 | class ActiveSupport::TestCase 6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 7 | fixtures :all 8 | 9 | # Add more helper methods to be used by all tests here... 10 | end 11 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Simplify/rails5_json_api_demo/dc24de7cea8bc3fc7b208c78ea57361a803c4285/tmp/.keep --------------------------------------------------------------------------------