├── log └── .keep ├── tmp └── .keep ├── vendor └── .keep ├── lib └── tasks │ └── .keep ├── .ruby-version ├── app ├── models │ ├── concerns │ │ └── .keep │ ├── application_record.rb │ ├── admin.rb │ ├── article.rb │ └── user.rb ├── controllers │ ├── concerns │ │ └── .keep │ ├── application_controller.rb │ └── api │ │ ├── backoffice │ │ ├── articles_controller.rb │ │ └── base_controller.rb │ │ └── client │ │ ├── articles_controller.rb │ │ └── base_controller.rb ├── views │ └── layouts │ │ ├── mailer.text.erb │ │ └── mailer.html.erb ├── jobs │ └── application_job.rb ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── mailers │ └── application_mailer.rb ├── decorators │ └── api │ │ ├── client │ │ ├── user_decorator.rb │ │ └── article_decorator.rb │ │ └── backoffice │ │ └── article_decorator.rb └── policies │ ├── api │ ├── backoffice │ │ └── article_policy.rb │ └── client │ │ └── article_policy.rb │ └── application_policy.rb ├── .rspec ├── .ruby-gemset ├── .dockerignore ├── config ├── database.yml.travis ├── initializers │ ├── filter_parameter_logging.rb │ ├── wrap_parameters.rb │ ├── cors.rb │ └── rswag_api.rb ├── spring.rb ├── environment.rb ├── cable.yml ├── boot.rb ├── routes.rb ├── database.yml ├── application.rb ├── locales │ └── en.yml ├── puma.rb └── environments │ ├── test.rb │ ├── development.rb │ └── production.rb ├── .env.example ├── public └── robots.txt ├── bin ├── bundle ├── rake ├── rails ├── spring ├── update └── setup ├── config.ru ├── db ├── migrate │ ├── 20190702191558_add_user_to_articles.rb │ ├── 20190713171929_add_username_to_users.rb │ ├── 20190629191433_create_articles.rb │ ├── 20190630154957_create_users.rb │ └── 20190713172514_create_admins.rb ├── seeds.rb └── schema.rb ├── spec ├── factories │ ├── admin.rb │ ├── users.rb │ └── articles.rb ├── spec_helper.rb ├── swagger_helper.rb ├── rails_helper.rb └── requests │ └── api │ ├── backoffice │ └── articles_spec.rb │ └── client │ └── articles_spec.rb ├── Dockerfile.development ├── Rakefile ├── .travis.yml ├── .gitignore ├── docker-compose.yml ├── README.md ├── Gemfile ├── .rubocop.yml └── Gemfile.lock /log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.3 2 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.ruby-gemset: -------------------------------------------------------------------------------- 1 | rswag-example 2 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .gitignore 3 | log/* 4 | tmp/* 5 | -------------------------------------------------------------------------------- /config/database.yml.travis: -------------------------------------------------------------------------------- 1 | test: 2 | adapter: postgresql 3 | database: travis_ci_test 4 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | DATABASE_HOST=localhost 2 | DATABASE_NAME= 3 | DATABASE_USERNAME= 4 | DATABASE_PASSWORD= 5 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationJob < ActiveJob::Base 4 | end 5 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::API 4 | end 5 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.config.filter_parameters += [:password] 4 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationRecord < ActiveRecord::Base 4 | self.abstract_class = true 5 | end 6 | -------------------------------------------------------------------------------- /app/models/admin.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Admin < ApplicationRecord 4 | has_secure_password 5 | has_secure_token :authentication_token 6 | end 7 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ActiveSupport.on_load(:action_controller) do 4 | wrap_parameters format: [:json] 5 | end 6 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationCable 4 | class Channel < ActionCable::Channel::Base 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /app/models/article.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Article < ApplicationRecord 4 | belongs_to :user 5 | 6 | validates :title, :body, presence: true 7 | end 8 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationCable 4 | class Connection < ActionCable::Connection::Base 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationMailer < ActionMailer::Base 4 | default from: 'from@example.com' 5 | layout 'mailer' 6 | end 7 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | %w[ 4 | .ruby-version 5 | .rbenv-vars 6 | tmp/restart.txt 7 | tmp/caching-dev.txt 8 | ].each { |path| Spring.watch(path) } 9 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is used by Rack-based servers to start the application. 4 | 5 | require_relative 'config/environment' 6 | 7 | run Rails.application 8 | -------------------------------------------------------------------------------- /db/migrate/20190702191558_add_user_to_articles.rb: -------------------------------------------------------------------------------- 1 | class AddUserToArticles < ActiveRecord::Migration[5.2] 2 | def change 3 | add_reference :articles, :user, foreign_key: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Load the Rails application. 4 | require_relative 'application' 5 | 6 | # Initialize the Rails application. 7 | Rails.application.initialize! 8 | -------------------------------------------------------------------------------- /spec/factories/admin.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :admin do 5 | email { FFaker::Internet.email } 6 | password { SecureRandom.hex } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :user do 5 | email { FFaker::Internet.email } 6 | password { SecureRandom.hex } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ApplicationRecord 4 | has_secure_password 5 | has_secure_token :authentication_token 6 | 7 | has_many :articles, dependent: :destroy 8 | end 9 | -------------------------------------------------------------------------------- /Dockerfile.development: -------------------------------------------------------------------------------- 1 | FROM ruby:2.6.3 2 | RUN apt-get update -yqq 3 | RUN apt-get install -yqq --no-install-recommends nodejs 4 | COPY . /usr/src/app/ 5 | COPY Gemfile* /usr/src/app/ 6 | WORKDIR /usr/src/app 7 | RUN bundle install 8 | -------------------------------------------------------------------------------- /db/migrate/20190713171929_add_username_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddUsernameToUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :users, :username, :string 4 | add_index :users, :username, unique: true 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/factories/articles.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :article do 5 | title { FFaker::Name.name } 6 | body { FFaker::Lorem.paragraphs(2) } 7 | association :user 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: async 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: rswag-example_production 11 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | require_relative '../config/boot' 8 | require 'rake' 9 | Rake.application.run 10 | -------------------------------------------------------------------------------- /db/migrate/20190629191433_create_articles.rb: -------------------------------------------------------------------------------- 1 | class CreateArticles < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :articles do |t| 4 | t.string :title 5 | t.text :body 6 | t.timestamps 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 4 | 5 | require 'bundler/setup' # Set up gems listed in the Gemfile. 6 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 7 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Add your own tasks in files placed in lib/tasks ending in .rake, 4 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 5 | 6 | require_relative 'config/application' 7 | 8 | Rails.application.load_tasks 9 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 4 | allow do 5 | origins '*' 6 | 7 | resource '*', 8 | headers: :any, 9 | methods: %i[get post put patch delete options head] 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | APP_PATH = File.expand_path('../config/application', __dir__) 8 | require_relative '../config/boot' 9 | require 'rails/commands' 10 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /db/migrate/20190630154957_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :users do |t| 4 | t.string :email 5 | t.string :password_digest 6 | t.string :authentication_token, null: false, index: { unique: true } 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20190713172514_create_admins.rb: -------------------------------------------------------------------------------- 1 | class CreateAdmins < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :admins do |t| 4 | t.string :email 5 | t.string :password_digest 6 | t.string :authentication_token, null: false, index: { unique: true } 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/decorators/api/client/user_decorator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Client 5 | class UserDecorator < Draper::Decorator 6 | delegate_all 7 | 8 | def as_json(*) 9 | json = { 10 | id: id, 11 | email: email 12 | } 13 | json 14 | end 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.configure do |config| 4 | config.expect_with :rspec do |expectations| 5 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 6 | end 7 | config.mock_with :rspec do |mocks| 8 | mocks.verify_partial_doubles = true 9 | end 10 | config.shared_context_metadata_behavior = :apply_to_host_groups 11 | end 12 | -------------------------------------------------------------------------------- /app/decorators/api/backoffice/article_decorator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Backoffice 5 | class ArticleDecorator < Draper::Decorator 6 | delegate_all 7 | 8 | def as_json(*) 9 | json = { 10 | id: id, 11 | title: title, 12 | body: body 13 | } 14 | json 15 | end 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | services: 3 | - postgresql 4 | before_script: 5 | - cp config/database.yml.travis config/database.yml 6 | - psql -c 'create database travis_ci_test;' -U postgres 7 | before_install: 8 | - gem update --system 9 | - gem install bundler 10 | cache: bundler 11 | language: ruby 12 | rvm: 13 | - 2.6.2 14 | script: 15 | - bundle exec rails db:migrate RAILS_ENV=test 16 | - bundle exec rspec 17 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | mount Rswag::Api::Engine => '/api/docs' unless Rails.env.production? 5 | namespace :api do 6 | namespace :backoffice do 7 | resources :articles, only: %i[index show update destroy] 8 | end 9 | namespace :client do 10 | resources :articles, only: %i[index show create update destroy] 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file should contain all the record creation needed to seed the database with its default values. 4 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 5 | # 6 | # Examples: 7 | # 8 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 9 | # Character.create(name: 'Luke', movie: movies.first) 10 | -------------------------------------------------------------------------------- /app/decorators/api/client/article_decorator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Client 5 | class ArticleDecorator < Draper::Decorator 6 | delegate_all 7 | 8 | decorates_association :user, with: UserDecorator 9 | 10 | def as_json(*) 11 | json = { 12 | id: id, 13 | title: title, 14 | body: body, 15 | user: user 16 | } 17 | json 18 | end 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | default: &default 2 | adapter: postgresql 3 | encoding: unicode 4 | host: <%= ENV['DATABASE_HOST'] %> 5 | username: <%= ENV['DATABASE_USERNAME'] %> 6 | password: <%= ENV['DATABASE_PASSWORD'] %> 7 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 8 | 9 | development: 10 | <<: *default 11 | database: rswag-example_development 12 | test: 13 | <<: *default 14 | database: rswag-example_test 15 | 16 | production: 17 | <<: *default 18 | database: <%= ENV['DATABASE_NAME'] %> 19 | 20 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads Spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require 'rubygems' 8 | require 'bundler' 9 | 10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) 11 | spring = lockfile.specs.detect { |spec| spec.name == 'spring' } 12 | if spring 13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 14 | gem 'spring', spring.version 15 | require 'spring/binstub' 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/policies/api/backoffice/article_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Backoffice 5 | class ArticlePolicy < ApplicationPolicy 6 | def index? 7 | true 8 | end 9 | 10 | def show? 11 | true 12 | end 13 | 14 | def create? 15 | false 16 | end 17 | 18 | def update? 19 | true 20 | end 21 | 22 | def destroy? 23 | true 24 | end 25 | 26 | class Scope < Scope 27 | def resolve 28 | scope.all 29 | end 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | 16 | # Ignore uploaded files in development 17 | /storage/* 18 | !/storage/.keep 19 | 20 | .byebug_history 21 | 22 | /swagger/swagger.json 23 | -------------------------------------------------------------------------------- /app/policies/api/client/article_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Client 5 | class ArticlePolicy < ApplicationPolicy 6 | def index? 7 | true 8 | end 9 | 10 | def show? 11 | true 12 | end 13 | 14 | def create? 15 | true 16 | end 17 | 18 | def update? 19 | record.user_id == user.id 20 | end 21 | 22 | def destroy? 23 | record.user_id == user.id 24 | end 25 | 26 | class Scope < Scope 27 | def resolve 28 | scope.all 29 | end 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | db: 4 | image: postgres:11.4 5 | volumes: 6 | - ./tmp/db:/var/lib/postgresql/data 7 | web: 8 | build: 9 | dockerfile: Dockerfile.development 10 | context: . 11 | ports: 12 | - "3000:3000" 13 | volumes: 14 | - .:/usr/src/app 15 | command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" 16 | depends_on: 17 | - db 18 | tty: true 19 | stdin_open: true 20 | environment: 21 | - RAILS_ENV=development 22 | - DATABASE_HOST=db 23 | - DATABASE_USERNAME=postgres 24 | - DATABASE_PASSWORD= 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | Demo how to use rswag-api, rswag-specs. 4 | 5 | 6 | ### Setup 7 | 8 | ``` 9 | cp .env.example .env 10 | rails db:create db:migrate 11 | rails server 12 | ``` 13 | 14 | ### Setup Docker 15 | ``` 16 | docker-compose build 17 | docker-compose up 18 | docker-compose run web rake db:create db:migrate 19 | open http://localhost:3000/ 20 | ``` 21 | Use `docker attach ID` to get into the running container, for detach without exit `Ctrl-p`, `Ctrl-q` 22 | 23 | ### Generate the Swagger JSON file 24 | 25 | ``` 26 | rake rswag:specs:swaggerize 27 | open http://localhost:3000/api/docs/client/swagger.json 28 | open http://localhost:3000/api/docs/backoffice/swagger.json 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/policies/application_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationPolicy 4 | attr_reader :user, :record 5 | 6 | def initialize(user, record) 7 | @user = user 8 | @record = record 9 | end 10 | 11 | def index? 12 | false 13 | end 14 | 15 | def show? 16 | false 17 | end 18 | 19 | def create? 20 | false 21 | end 22 | 23 | def update? 24 | false 25 | end 26 | 27 | def destroy? 28 | false 29 | end 30 | 31 | class Scope 32 | attr_reader :user, :scope 33 | 34 | def initialize(user, scope) 35 | @user = user 36 | @scope = scope 37 | end 38 | 39 | def resolve 40 | scope.all 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /config/initializers/rswag_api.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rswag::Api.configure do |c| 4 | # Specify a root folder where Swagger JSON files are located 5 | # This is used by the Swagger middleware to serve requests for API descriptions 6 | # NOTE: If you're using rswag-specs to generate Swagger, you'll need to ensure 7 | # that it's configured to generate files in the same folder 8 | c.swagger_root = Rails.root.to_s + '/swagger' 9 | 10 | # Inject a lamda function to alter the returned Swagger prior to serialization 11 | # The function will have access to the rack env for the current request 12 | # For example, you could leverage this to dynamically assign the "host" property 13 | # 14 | c.swagger_filter = lambda { |swagger, env| 15 | swagger['host'] = env['HTTP_HOST'] 16 | } 17 | end 18 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | puts "\n== Updating database ==" 21 | system! 'bin/rails db:migrate' 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system! 'bin/rails log:clear tmp:clear' 25 | 26 | puts "\n== Restarting application server ==" 27 | system! 'bin/rails restart' 28 | end 29 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'boot' 4 | 5 | require 'rails' 6 | require 'active_model/railtie' 7 | require 'active_job/railtie' 8 | require 'active_record/railtie' 9 | require 'action_controller/railtie' 10 | require 'action_mailer/railtie' 11 | require 'action_view/railtie' 12 | require 'action_cable/engine' 13 | require 'rails/test_unit/railtie' 14 | 15 | Bundler.require(*Rails.groups) 16 | 17 | module RswagExample 18 | class Application < Rails::Application 19 | config.load_defaults 5.2 20 | config.api_only = true 21 | 22 | config.generators do |g| 23 | g.test_framework :rspec, 24 | view_specs: false, 25 | helper_specs: false, 26 | routing_specs: false, 27 | controller_specs: false 28 | end 29 | end 30 | end 31 | RSpec.configure do |config| 32 | config.swagger_dry_run = false 33 | end 34 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 5 | 6 | gem 'bcrypt' 7 | gem 'bootsnap', '>= 1.1.0', require: false 8 | gem 'dotenv-rails' 9 | gem 'draper' 10 | gem 'pagy' 11 | gem 'pg', '>= 0.18', '< 2.0' 12 | gem 'puma', '~> 4.3' 13 | gem 'pundit' 14 | gem 'rack-cors' 15 | gem 'rails', '~> 6.0.3' 16 | gem 'rswag-api' 17 | 18 | group :development, :test do 19 | gem 'factory_bot_rails' 20 | gem 'ffaker' 21 | gem 'pry-rails' 22 | gem 'rspec-rails' 23 | gem 'rswag-specs' 24 | end 25 | 26 | group :development do 27 | gem 'listen', '>= 3.0.5', '< 3.5' 28 | gem 'rubocop', require: false 29 | gem 'rubocop-performance', require: false 30 | gem 'rubocop-rails', require: false 31 | gem 'rubocop-thread_safety', require: false 32 | gem 'spring' 33 | gem 'spring-watcher-listen', '~> 2.0.0' 34 | end 35 | 36 | group :test do 37 | gem 'database_cleaner' 38 | end 39 | -------------------------------------------------------------------------------- /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 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at http://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a starting point to setup your application. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:setup' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /spec/swagger_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.configure do |config| 6 | CLIENT_DOC = 'client/swagger.json' 7 | BACKOFFICE_DOC = 'backoffice/swagger.json' 8 | config.swagger_root = Rswag::Api.config.swagger_root 9 | config.swagger_docs = { 10 | CLIENT_DOC => { 11 | swagger: '2.0', 12 | info: { 13 | title: 'Rswag Example REST API Client', 14 | version: '1.0.0', 15 | description: 'Rswag Example REST API Client' 16 | }, 17 | host: '', 18 | basePath: '/', 19 | paths: {}, 20 | schemes: %w[ 21 | http 22 | https 23 | ], 24 | consumes: ['application/json'] 25 | }, 26 | BACKOFFICE_DOC => { 27 | swagger: '2.0', 28 | info: { 29 | title: 'Rswag Example REST API Backoffice', 30 | version: '1.0.0', 31 | description: 'Rswag Example REST API Backoffice' 32 | }, 33 | host: '', 34 | basePath: '/', 35 | paths: {}, 36 | schemes: %w[ 37 | http 38 | https 39 | ], 40 | consumes: ['application/json'] 41 | } 42 | } 43 | end 44 | -------------------------------------------------------------------------------- /app/controllers/api/backoffice/articles_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Backoffice 5 | class ArticlesController < BaseController 6 | before_action :authenticate!, only: %i[create update destroy] 7 | 8 | def index 9 | articles = policy_scope(Article.all, policy_scope_class: ArticlePolicy::Scope) 10 | render json: render_collection(articles) 11 | end 12 | 13 | def show 14 | authorize(article, :show?, policy_class: ArticlePolicy) 15 | render json: render_resource(article) 16 | end 17 | 18 | def update 19 | authorize(article, :update?, policy_class: ArticlePolicy) 20 | if article.update(resource_params) 21 | render json: render_resource(article), status: :ok 22 | else 23 | render json: render_errors(article), status: :unprocessable_entity 24 | end 25 | end 26 | 27 | def destroy 28 | authorize(article, :destroy?, policy_class: ArticlePolicy) 29 | article.destroy 30 | head :no_content 31 | end 32 | 33 | private 34 | 35 | def article 36 | @article ||= Article.find(params[:id]) 37 | end 38 | 39 | def resource_params 40 | params.permit(:title, :body) 41 | end 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'spec_helper' 4 | ENV['RAILS_ENV'] ||= 'test' 5 | require File.expand_path('../config/environment', __dir__) 6 | abort('The Rails environment is running in production mode!') if Rails.env.production? 7 | require 'rspec/rails' 8 | require 'database_cleaner' 9 | 10 | Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 11 | 12 | begin 13 | ActiveRecord::Migration.maintain_test_schema! 14 | rescue ActiveRecord::PendingMigrationError => e 15 | puts e.to_s.strip 16 | exit 1 17 | end 18 | RSpec.configure do |config| 19 | config.order = :random 20 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 21 | config.use_transactional_fixtures = true 22 | config.infer_spec_type_from_file_location! 23 | config.filter_rails_from_backtrace! 24 | config.include FactoryBot::Syntax::Methods 25 | config.before(:suite) do 26 | DatabaseCleaner.clean_with(:truncation) 27 | DatabaseCleaner.strategy = :transaction 28 | end 29 | 30 | config.around(:each) do |example| 31 | DatabaseCleaner.cleaning do 32 | example.run 33 | end 34 | end 35 | 36 | config.after(:each, type: :request) do |example| 37 | next if response&.body&.empty? 38 | 39 | example.metadata[:response][:examples] = { 'application/json' => JSON.parse(response.body, symbolize_names: true) } 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Puma can serve each request in a thread from an internal thread pool. 4 | # The `threads` method setting takes two numbers: a minimum and maximum. 5 | # Any libraries that use thread pools should be configured to match 6 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 7 | # and maximum; this matches the default thread size of Active Record. 8 | # 9 | threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } 10 | threads threads_count, threads_count 11 | 12 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 13 | # 14 | port ENV.fetch('PORT') { 3000 } 15 | 16 | # Specifies the `environment` that Puma will run in. 17 | # 18 | environment ENV.fetch('RAILS_ENV') { 'development' } 19 | 20 | # Specifies the number of `workers` to boot in clustered mode. 21 | # Workers are forked webserver processes. If using threads and workers together 22 | # the concurrency of the application would be max `threads` * `workers`. 23 | # Workers do not work on JRuby or Windows (both of which do not support 24 | # processes). 25 | # 26 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 27 | 28 | # Use the `preload_app!` method when specifying a `workers` number. 29 | # This directive tells Puma to first boot the application and load code 30 | # before forking the application. This takes advantage of Copy On Write 31 | # process behavior so workers use less memory. 32 | # 33 | # preload_app! 34 | 35 | # Allow puma to be restarted by `rails restart` command. 36 | plugin :tmp_restart 37 | -------------------------------------------------------------------------------- /app/controllers/api/client/articles_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Client 5 | class ArticlesController < BaseController 6 | before_action :authenticate!, only: %i[create update destroy] 7 | 8 | def index 9 | articles = policy_scope(Article.all, policy_scope_class: ArticlePolicy::Scope) 10 | render json: render_collection(articles) 11 | end 12 | 13 | def show 14 | authorize(article, :show?, policy_class: ArticlePolicy) 15 | render json: render_resource(article) 16 | end 17 | 18 | def create 19 | @article = current_user.articles.build(resource_params) 20 | authorize(@article, :create?, policy_class: ArticlePolicy) 21 | if @article.save 22 | render json: render_resource(@article), status: :created 23 | else 24 | render json: render_errors(@article), status: :unprocessable_entity 25 | end 26 | end 27 | 28 | def update 29 | authorize(article, :update?, policy_class: ArticlePolicy) 30 | if article.update(resource_params) 31 | render json: render_resource(article), status: :ok 32 | else 33 | render json: render_errors(article), status: :unprocessable_entity 34 | end 35 | end 36 | 37 | def destroy 38 | authorize(article, :destroy?, policy_class: ArticlePolicy) 39 | article.destroy 40 | head :no_content 41 | end 42 | 43 | private 44 | 45 | def article 46 | @article ||= Article.find(params[:id]) 47 | end 48 | 49 | def resource_params 50 | params.permit(:title, :body) 51 | end 52 | end 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | require: 2 | - rubocop/cop/internal_affairs 3 | - rubocop-performance 4 | - rubocop-thread_safety 5 | - rubocop-rails 6 | 7 | AllCops: 8 | Exclude: 9 | - 'vendor/**/*' 10 | - 'tmp/**/*' 11 | - 'bin/*' 12 | - 'db/migrate/*' 13 | - 'db/schema.rb' 14 | TargetRailsVersion: 5.2.3 15 | TargetRubyVersion: 2.6.2 16 | DisplayCopNames: true 17 | DisplayStyleGuide: true 18 | 19 | Rails: 20 | Enabled: true 21 | 22 | Rails/FilePath: 23 | EnforcedStyle: slashes 24 | 25 | Rails/LexicallyScopedActionFilter: 26 | Enabled: false 27 | 28 | Metrics/LineLength: 29 | Max: 120 30 | 31 | Metrics/MethodLength: 32 | ExcludedMethods: 33 | - as_json 34 | 35 | Metrics/BlockLength: 36 | Exclude: 37 | - 'lib/capistrano/tasks/**/*' 38 | - 'lib/tasks/**/*' 39 | - 'spec/**/*' 40 | 41 | Style/FrozenStringLiteralComment: 42 | EnforcedStyle: always 43 | 44 | Style/Documentation: 45 | Enabled: false 46 | 47 | Style/MethodDefParentheses: 48 | Enabled: false 49 | 50 | Layout/ClassStructure: 51 | Enabled: true 52 | ExpectedOrder: 53 | - module_inclusion 54 | - constants 55 | - association 56 | - public_attribute_macros 57 | - public_delegate 58 | - macros 59 | - public_class_methods 60 | - initializer 61 | - public_methods 62 | - protected_attribute_macros 63 | - protected_methods 64 | - private_attribute_macros 65 | - private_delegate 66 | - private_methods 67 | 68 | Layout/AlignParameters: 69 | EnforcedStyle: with_fixed_indentation 70 | 71 | Layout/AlignArguments: 72 | EnforcedStyle: with_fixed_indentation 73 | 74 | Layout/IndentFirstHashElement: 75 | EnforcedStyle: consistent 76 | 77 | Layout/ExtraSpacing: 78 | AllowForAlignment: true 79 | -------------------------------------------------------------------------------- /app/controllers/api/client/base_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Client 5 | class BaseController < ApplicationController 6 | include ActionController::HttpAuthentication::Token::ControllerMethods 7 | include Pagy::Backend 8 | include Pundit 9 | 10 | before_action :authenticate! 11 | after_action :verify_authorized, except: :index 12 | after_action :verify_policy_scoped, only: :index 13 | 14 | attr_reader :current_user 15 | 16 | private 17 | 18 | rescue_from ActiveRecord::RecordNotFound, with: :not_found 19 | rescue_from Pundit::NotAuthorizedError, with: :not_authorized 20 | 21 | def not_found 22 | render json: { errors: ['Not Found'] }, status: :not_found 23 | end 24 | 25 | def not_authorized 26 | render json: { errors: ['Not Authorized'] }, status: :not_authorized 27 | end 28 | 29 | def render_collection(relation) 30 | pagy, items = pagy(relation, items: 25) 31 | { 32 | collection: "#{controller_path.classify}Decorator".constantize.decorate_collection(items), 33 | total_pages: pagy.pages, 34 | total_count: pagy.count, 35 | current_page: pagy.page 36 | } 37 | end 38 | 39 | def render_resource(resource) 40 | "#{controller_path.classify}Decorator".constantize.decorate(resource) 41 | end 42 | 43 | def render_errors(resource) 44 | { 45 | errors: resource.errors 46 | } 47 | end 48 | 49 | def authenticate! 50 | result = authenticate_with_http_token do |token| 51 | @current_user = User.find_by(authentication_token: token) 52 | end 53 | render json: { errors: ['Unauthorized'] }, status: :unauthorized unless result 54 | end 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/api/backoffice/base_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Api 4 | module Backoffice 5 | class BaseController < ApplicationController 6 | include ActionController::HttpAuthentication::Token::ControllerMethods 7 | include Pagy::Backend 8 | include Pundit 9 | 10 | before_action :authenticate! 11 | after_action :verify_authorized, except: :index 12 | after_action :verify_policy_scoped, only: :index 13 | 14 | attr_reader :current_user 15 | 16 | private 17 | 18 | rescue_from ActiveRecord::RecordNotFound, with: :not_found 19 | rescue_from Pundit::NotAuthorizedError, with: :not_authorized 20 | 21 | def not_found 22 | render json: { errors: ['Not Found'] }, status: :not_found 23 | end 24 | 25 | def not_authorized 26 | render json: { errors: ['Not Authorized'] }, status: :not_authorized 27 | end 28 | 29 | def render_collection(relation) 30 | pagy, items = pagy(relation, items: 25) 31 | { 32 | collection: "#{controller_path.classify}Decorator".constantize.decorate_collection(items), 33 | total_pages: pagy.pages, 34 | total_count: pagy.count, 35 | current_page: pagy.page 36 | } 37 | end 38 | 39 | def render_resource(resource) 40 | "#{controller_path.classify}Decorator".constantize.decorate(resource) 41 | end 42 | 43 | def render_errors(resource) 44 | { 45 | errors: resource.errors 46 | } 47 | end 48 | 49 | def authenticate! 50 | result = authenticate_with_http_token do |token| 51 | @current_user = Admin.find_by(authentication_token: token) 52 | end 53 | render json: { errors: ['Unauthorized'] }, status: :unauthorized unless result 54 | end 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # The test environment is used exclusively to run your application's 7 | # test suite. You never need to work with it otherwise. Remember that 8 | # your test database is "scratch space" for the test suite and is wiped 9 | # and recreated between test runs. Don't rely on the data there! 10 | config.cache_classes = true 11 | 12 | # Do not eager load code on boot. This avoids loading your whole application 13 | # just for the purpose of running a single test. If you are using a tool that 14 | # preloads Rails for running tests, you may have to set it to true. 15 | config.eager_load = false 16 | 17 | # Configure public file server for tests with Cache-Control for performance. 18 | config.public_file_server.enabled = true 19 | config.public_file_server.headers = { 20 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 21 | } 22 | 23 | # Show full error reports and disable caching. 24 | config.consider_all_requests_local = true 25 | config.action_controller.perform_caching = false 26 | 27 | # Raise exceptions instead of rendering exception templates. 28 | config.action_dispatch.show_exceptions = false 29 | 30 | # Disable request forgery protection in test environment. 31 | config.action_controller.allow_forgery_protection = false 32 | 33 | config.action_mailer.perform_caching = false 34 | 35 | # Tell Action Mailer not to deliver emails to the real world. 36 | # The :test delivery method accumulates sent emails in the 37 | # ActionMailer::Base.deliveries array. 38 | config.action_mailer.delivery_method = :test 39 | 40 | # Print deprecation notices to the stderr. 41 | config.active_support.deprecation = :stderr 42 | 43 | # Raises error for missing translations 44 | # config.action_view.raise_on_missing_translations = true 45 | end 46 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded on 7 | # every request. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp/caching-dev.txt').exist? 20 | config.action_controller.perform_caching = true 21 | 22 | config.cache_store = :memory_store 23 | config.public_file_server.headers = { 24 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 25 | } 26 | else 27 | config.action_controller.perform_caching = false 28 | 29 | config.cache_store = :null_store 30 | end 31 | 32 | # Don't care if the mailer can't send. 33 | config.action_mailer.raise_delivery_errors = false 34 | 35 | config.action_mailer.perform_caching = false 36 | 37 | # Print deprecation notices to the Rails logger. 38 | config.active_support.deprecation = :log 39 | 40 | # Raise an error on page load if there are pending migrations. 41 | config.active_record.migration_error = :page_load 42 | 43 | # Highlight code that triggered database queries in logs. 44 | config.active_record.verbose_query_logs = true 45 | 46 | # Raises error for missing translations 47 | # config.action_view.raise_on_missing_translations = true 48 | 49 | # Use an evented file watcher to asynchronously detect changes in source code, 50 | # routes, locales, etc. This feature depends on the listen gem. 51 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 52 | end 53 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2019_07_13_172514) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "admins", force: :cascade do |t| 19 | t.string "email" 20 | t.string "password_digest" 21 | t.string "authentication_token", null: false 22 | t.datetime "created_at", null: false 23 | t.datetime "updated_at", null: false 24 | t.index ["authentication_token"], name: "index_admins_on_authentication_token", unique: true 25 | end 26 | 27 | create_table "articles", force: :cascade do |t| 28 | t.string "title" 29 | t.text "body" 30 | t.datetime "created_at", null: false 31 | t.datetime "updated_at", null: false 32 | t.bigint "user_id" 33 | t.index ["user_id"], name: "index_articles_on_user_id" 34 | end 35 | 36 | create_table "users", force: :cascade do |t| 37 | t.string "email" 38 | t.string "password_digest" 39 | t.string "authentication_token", null: false 40 | t.datetime "created_at", null: false 41 | t.datetime "updated_at", null: false 42 | t.string "username" 43 | t.index ["authentication_token"], name: "index_users_on_authentication_token", unique: true 44 | t.index ["username"], name: "index_users_on_username", unique: true 45 | end 46 | 47 | add_foreign_key "articles", "users" 48 | end 49 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | config.action_controller.perform_caching = true 18 | 19 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 20 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 21 | # config.require_master_key = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 28 | # config.action_controller.asset_host = 'http://assets.example.com' 29 | 30 | # Specifies the header that your server uses for sending files. 31 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 32 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 33 | 34 | # Mount Action Cable outside main process or domain 35 | # config.action_cable.mount_path = nil 36 | # config.action_cable.url = 'wss://example.com/cable' 37 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 38 | 39 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 40 | # config.force_ssl = true 41 | 42 | # Use the lowest log level to ensure availability of diagnostic information 43 | # when problems arise. 44 | config.log_level = :debug 45 | 46 | # Prepend all log lines with the following tags. 47 | config.log_tags = [:request_id] 48 | 49 | # Use a different cache store in production. 50 | # config.cache_store = :mem_cache_store 51 | 52 | # Use a real queuing backend for Active Job (and separate queues per environment) 53 | # config.active_job.queue_adapter = :resque 54 | # config.active_job.queue_name_prefix = "rswag-example_#{Rails.env}" 55 | 56 | config.action_mailer.perform_caching = false 57 | 58 | # Ignore bad email addresses and do not raise email delivery errors. 59 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 60 | # config.action_mailer.raise_delivery_errors = false 61 | 62 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 63 | # the I18n.default_locale when a translation cannot be found). 64 | config.i18n.fallbacks = true 65 | 66 | # Send deprecation notices to registered listeners. 67 | config.active_support.deprecation = :notify 68 | 69 | # Use default logging formatter so that PID and timestamp are not suppressed. 70 | config.log_formatter = ::Logger::Formatter.new 71 | 72 | # Use a different logger for distributed setups. 73 | # require 'syslog/logger' 74 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 75 | 76 | if ENV['RAILS_LOG_TO_STDOUT'].present? 77 | logger = ActiveSupport::Logger.new(STDOUT) 78 | logger.formatter = config.log_formatter 79 | config.logger = ActiveSupport::TaggedLogging.new(logger) 80 | end 81 | 82 | # Do not dump schema after migrations. 83 | config.active_record.dump_schema_after_migration = false 84 | end 85 | -------------------------------------------------------------------------------- /spec/requests/api/backoffice/articles_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'swagger_helper' 4 | 5 | describe 'Articles', swagger_doc: BACKOFFICE_DOC do 6 | path '/api/backoffice/articles' do 7 | get 'Find all articles' do 8 | tags 'Articles' 9 | parameter name: :page, in: :query, type: :integer, description: 'Page number. Default: 1', required: false 10 | parameter name: :per_page, in: :query, type: :integer, description: 'Per page items. Default: 25', required: false 11 | 12 | response '200', :success do 13 | schema type: :object, 14 | properties: { 15 | collection: { 16 | type: :array, 17 | items: { 18 | type: :object, 19 | properties: { 20 | id: { type: :integer }, 21 | title: { type: :string }, 22 | body: { type: :string } 23 | } 24 | } 25 | } 26 | } 27 | let!(:article) { create(:article) } 28 | run_test! 29 | end 30 | end 31 | end 32 | 33 | path '/api/backoffice/articles/{id}' do 34 | get 'Find article by id' do 35 | tags 'Articles' 36 | parameter name: :id, in: :path, type: :integer 37 | response '200', :success do 38 | schema type: :object, 39 | properties: { 40 | id: { type: :integer }, 41 | title: { type: :string }, 42 | body: { type: :string } 43 | } 44 | let!(:id) { create(:article).id } 45 | run_test! 46 | end 47 | 48 | response '404', :not_found do 49 | let!(:id) { 'invalid' } 50 | run_test! 51 | end 52 | end 53 | 54 | put 'Update article by id' do 55 | tags 'Articles' 56 | parameter name: :id, in: :path, type: :integer 57 | parameter name: 'Authorization', in: :header, type: :string, default: 'Bearer c36e6eadde881ca7' 58 | parameter name: :article, in: :body, schema: { 59 | type: :object, 60 | properties: { 61 | title: { type: :string }, 62 | body: { type: :string } 63 | }, 64 | required: %w[title body] 65 | } 66 | response '200', :success do 67 | let!(:admin) { create(:admin) } 68 | let!(:user) { create(:user) } 69 | let!(:id) { create(:article, user: user).id } 70 | let(:Authorization) { 'Bearer ' + admin.authentication_token } 71 | let(:article) { { title: 'Title', body: 'Body' } } 72 | run_test! 73 | end 74 | 75 | response '404', :not_found do 76 | let!(:admin) { create(:admin) } 77 | let!(:user) { create(:user) } 78 | let(:Authorization) { 'Bearer ' + admin.authentication_token } 79 | let(:article) { { title: 'Title', body: 'Body' } } 80 | let!(:id) { 'invalid' } 81 | run_test! 82 | end 83 | end 84 | 85 | delete 'Delete article by id' do 86 | tags 'Articles' 87 | parameter name: :id, in: :path, type: :integer 88 | parameter name: 'Authorization', in: :header, type: :string, default: 'Bearer c36e6eadde881ca7' 89 | response '204', :no_content do 90 | let!(:admin) { create(:admin) } 91 | let!(:user) { create(:user) } 92 | let(:Authorization) { 'Bearer ' + admin.authentication_token } 93 | let!(:id) { create(:article, user: user).id } 94 | run_test! 95 | end 96 | 97 | response '404', :not_found do 98 | let!(:admin) { create(:admin) } 99 | let!(:user) { create(:user) } 100 | let(:Authorization) { 'Bearer ' + admin.authentication_token } 101 | let!(:id) { 'invalid' } 102 | run_test! 103 | end 104 | end 105 | end 106 | end 107 | -------------------------------------------------------------------------------- /spec/requests/api/client/articles_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'swagger_helper' 4 | 5 | describe 'Articles', swagger_doc: CLIENT_DOC do 6 | path '/api/client/articles' do 7 | get 'Find all articles' do 8 | tags 'Articles' 9 | parameter name: :page, in: :query, type: :integer, description: 'Page number. Default: 1', required: false 10 | parameter name: :per_page, in: :query, type: :integer, description: 'Per page items. Default: 25', required: false 11 | 12 | response '200', :success do 13 | schema type: :object, 14 | properties: { 15 | collection: { 16 | type: :array, 17 | items: { 18 | type: :object, 19 | properties: { 20 | id: { type: :integer }, 21 | title: { type: :string }, 22 | body: { type: :string }, 23 | user: { 24 | type: :object, 25 | properties: { 26 | id: { type: :integer }, 27 | email: { type: :string }, 28 | username: { type: :string, 'x-nullable': true } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } 35 | let!(:article) { create(:article) } 36 | run_test! 37 | end 38 | end 39 | 40 | post 'Create new article' do 41 | tags 'Articles' 42 | parameter name: 'Authorization', in: :header, type: :string, default: 'Bearer c36e6eadde881ca7' 43 | parameter name: :article, in: :body, schema: { 44 | type: :object, 45 | properties: { 46 | title: { type: :string }, 47 | body: { type: :string } 48 | }, 49 | required: %w[title body] 50 | } 51 | 52 | response '401', :unauthorized do 53 | let(:Authorization) { '' } 54 | let(:article) { { title: '22', body: '23423' } } 55 | run_test! 56 | end 57 | 58 | response '201', :created do 59 | let!(:user) { create(:user) } 60 | let(:Authorization) { 'Bearer ' + user.authentication_token } 61 | let(:article) { { title: '22', body: '23423' } } 62 | run_test! 63 | end 64 | 65 | response '422', :invalid_request do 66 | let!(:user) { create(:user) } 67 | let(:Authorization) { 'Bearer ' + user.authentication_token } 68 | let(:article) { { title: '22' } } 69 | run_test! 70 | end 71 | end 72 | end 73 | 74 | path '/api/client/articles/{id}' do 75 | get 'Find article by id' do 76 | tags 'Articles' 77 | parameter name: :id, in: :path, type: :integer 78 | response '200', :success do 79 | schema type: :object, 80 | properties: { 81 | id: { type: :integer }, 82 | title: { type: :string }, 83 | body: { type: :string }, 84 | user: { 85 | type: :object, 86 | properties: { 87 | id: { type: :integer }, 88 | email: { type: :string }, 89 | username: { type: :string, 'x-nullable': true } 90 | } 91 | } 92 | } 93 | let!(:id) { create(:article).id } 94 | run_test! 95 | end 96 | 97 | response '404', :not_found do 98 | let!(:id) { 'invalid' } 99 | run_test! 100 | end 101 | end 102 | 103 | put 'Update article by id' do 104 | tags 'Articles' 105 | parameter name: :id, in: :path, type: :integer 106 | parameter name: 'Authorization', in: :header, type: :string, default: 'Bearer c36e6eadde881ca7' 107 | parameter name: :article, in: :body, schema: { 108 | type: :object, 109 | properties: { 110 | title: { type: :string }, 111 | body: { type: :string } 112 | }, 113 | required: %w[title body] 114 | } 115 | response '200', :success do 116 | let!(:user) { create(:user) } 117 | let!(:id) { create(:article, user: user).id } 118 | let(:Authorization) { 'Bearer ' + user.authentication_token } 119 | let(:article) { { title: 'Title', body: 'Body' } } 120 | run_test! 121 | end 122 | 123 | response '404', :not_found do 124 | let!(:user) { create(:user) } 125 | let(:Authorization) { 'Bearer ' + user.authentication_token } 126 | let(:article) { { title: 'Title', body: 'Body' } } 127 | let!(:id) { 'invalid' } 128 | run_test! 129 | end 130 | end 131 | 132 | delete 'Delete article by id' do 133 | tags 'Articles' 134 | parameter name: :id, in: :path, type: :integer 135 | parameter name: 'Authorization', in: :header, type: :string, default: 'Bearer c36e6eadde881ca7' 136 | response '204', :no_content do 137 | let!(:user) { create(:user) } 138 | let(:Authorization) { 'Bearer ' + user.authentication_token } 139 | let!(:id) { create(:article, user: user).id } 140 | run_test! 141 | end 142 | 143 | response '404', :not_found do 144 | let!(:user) { create(:user) } 145 | let(:Authorization) { 'Bearer ' + user.authentication_token } 146 | let!(:id) { 'invalid' } 147 | run_test! 148 | end 149 | end 150 | end 151 | end 152 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.0.3.1) 5 | actionpack (= 6.0.3.1) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailbox (6.0.3.1) 9 | actionpack (= 6.0.3.1) 10 | activejob (= 6.0.3.1) 11 | activerecord (= 6.0.3.1) 12 | activestorage (= 6.0.3.1) 13 | activesupport (= 6.0.3.1) 14 | mail (>= 2.7.1) 15 | actionmailer (6.0.3.1) 16 | actionpack (= 6.0.3.1) 17 | actionview (= 6.0.3.1) 18 | activejob (= 6.0.3.1) 19 | mail (~> 2.5, >= 2.5.4) 20 | rails-dom-testing (~> 2.0) 21 | actionpack (6.0.3.1) 22 | actionview (= 6.0.3.1) 23 | activesupport (= 6.0.3.1) 24 | rack (~> 2.0, >= 2.0.8) 25 | rack-test (>= 0.6.3) 26 | rails-dom-testing (~> 2.0) 27 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 28 | actiontext (6.0.3.1) 29 | actionpack (= 6.0.3.1) 30 | activerecord (= 6.0.3.1) 31 | activestorage (= 6.0.3.1) 32 | activesupport (= 6.0.3.1) 33 | nokogiri (>= 1.8.5) 34 | actionview (6.0.3.1) 35 | activesupport (= 6.0.3.1) 36 | builder (~> 3.1) 37 | erubi (~> 1.4) 38 | rails-dom-testing (~> 2.0) 39 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 40 | activejob (6.0.3.1) 41 | activesupport (= 6.0.3.1) 42 | globalid (>= 0.3.6) 43 | activemodel (6.0.3.1) 44 | activesupport (= 6.0.3.1) 45 | activemodel-serializers-xml (1.0.2) 46 | activemodel (> 5.x) 47 | activesupport (> 5.x) 48 | builder (~> 3.1) 49 | activerecord (6.0.3.1) 50 | activemodel (= 6.0.3.1) 51 | activesupport (= 6.0.3.1) 52 | activestorage (6.0.3.1) 53 | actionpack (= 6.0.3.1) 54 | activejob (= 6.0.3.1) 55 | activerecord (= 6.0.3.1) 56 | marcel (~> 0.3.1) 57 | activesupport (6.0.3.1) 58 | concurrent-ruby (~> 1.0, >= 1.0.2) 59 | i18n (>= 0.7, < 2) 60 | minitest (~> 5.1) 61 | tzinfo (~> 1.1) 62 | zeitwerk (~> 2.2, >= 2.2.2) 63 | addressable (2.7.0) 64 | public_suffix (>= 2.0.2, < 5.0) 65 | ast (2.4.0) 66 | bcrypt (3.1.13) 67 | bootsnap (1.4.6) 68 | msgpack (~> 1.0) 69 | builder (3.2.4) 70 | coderay (1.1.2) 71 | concurrent-ruby (1.1.8) 72 | crass (1.0.6) 73 | database_cleaner (2.0.1) 74 | database_cleaner-active_record (~> 2.0.0) 75 | database_cleaner-active_record (2.0.0) 76 | activerecord (>= 5.a) 77 | database_cleaner-core (~> 2.0.0) 78 | database_cleaner-core (2.0.1) 79 | diff-lcs (1.4.4) 80 | dotenv (2.7.5) 81 | dotenv-rails (2.7.5) 82 | dotenv (= 2.7.5) 83 | railties (>= 3.2, < 6.1) 84 | draper (4.0.1) 85 | actionpack (>= 5.0) 86 | activemodel (>= 5.0) 87 | activemodel-serializers-xml (>= 1.0) 88 | activesupport (>= 5.0) 89 | request_store (>= 1.0) 90 | erubi (1.10.0) 91 | factory_bot (5.2.0) 92 | activesupport (>= 4.2.0) 93 | factory_bot_rails (5.2.0) 94 | factory_bot (~> 5.2.0) 95 | railties (>= 4.2.0) 96 | ffaker (2.15.0) 97 | ffi (1.14.2) 98 | globalid (0.4.2) 99 | activesupport (>= 4.2.0) 100 | i18n (1.8.8) 101 | concurrent-ruby (~> 1.0) 102 | json-schema (2.8.1) 103 | addressable (>= 2.4) 104 | listen (3.4.1) 105 | rb-fsevent (~> 0.10, >= 0.10.3) 106 | rb-inotify (~> 0.9, >= 0.9.10) 107 | loofah (2.9.0) 108 | crass (~> 1.0.2) 109 | nokogiri (>= 1.5.9) 110 | mail (2.7.1) 111 | mini_mime (>= 0.1.1) 112 | marcel (0.3.3) 113 | mimemagic (~> 0.3.2) 114 | method_source (0.9.2) 115 | mimemagic (0.3.5) 116 | mini_mime (1.0.2) 117 | mini_portile2 (2.5.0) 118 | minitest (5.14.3) 119 | msgpack (1.3.3) 120 | nio4r (2.5.2) 121 | nokogiri (1.11.1) 122 | mini_portile2 (~> 2.5.0) 123 | racc (~> 1.4) 124 | pagy (3.10.0) 125 | parallel (1.19.1) 126 | parser (2.7.1.3) 127 | ast (~> 2.4.0) 128 | pg (1.2.3) 129 | pry (0.12.2) 130 | coderay (~> 1.1.0) 131 | method_source (~> 0.9.0) 132 | pry-rails (0.3.9) 133 | pry (>= 0.10.4) 134 | public_suffix (4.0.5) 135 | puma (4.3.5) 136 | nio4r (~> 2.0) 137 | pundit (2.1.0) 138 | activesupport (>= 3.0.0) 139 | racc (1.5.2) 140 | rack (2.2.3) 141 | rack-cors (1.1.1) 142 | rack (>= 2.0.0) 143 | rack-test (1.1.0) 144 | rack (>= 1.0, < 3) 145 | rails (6.0.3.1) 146 | actioncable (= 6.0.3.1) 147 | actionmailbox (= 6.0.3.1) 148 | actionmailer (= 6.0.3.1) 149 | actionpack (= 6.0.3.1) 150 | actiontext (= 6.0.3.1) 151 | actionview (= 6.0.3.1) 152 | activejob (= 6.0.3.1) 153 | activemodel (= 6.0.3.1) 154 | activerecord (= 6.0.3.1) 155 | activestorage (= 6.0.3.1) 156 | activesupport (= 6.0.3.1) 157 | bundler (>= 1.3.0) 158 | railties (= 6.0.3.1) 159 | sprockets-rails (>= 2.0.0) 160 | rails-dom-testing (2.0.3) 161 | activesupport (>= 4.2.0) 162 | nokogiri (>= 1.6) 163 | rails-html-sanitizer (1.3.0) 164 | loofah (~> 2.3) 165 | railties (6.0.3.1) 166 | actionpack (= 6.0.3.1) 167 | activesupport (= 6.0.3.1) 168 | method_source 169 | rake (>= 0.8.7) 170 | thor (>= 0.20.3, < 2.0) 171 | rainbow (3.0.0) 172 | rake (13.0.3) 173 | rb-fsevent (0.10.4) 174 | rb-inotify (0.10.1) 175 | ffi (~> 1.0) 176 | request_store (1.5.0) 177 | rack (>= 1.4) 178 | rexml (3.2.4) 179 | rspec-core (3.10.1) 180 | rspec-support (~> 3.10.0) 181 | rspec-expectations (3.10.1) 182 | diff-lcs (>= 1.2.0, < 2.0) 183 | rspec-support (~> 3.10.0) 184 | rspec-mocks (3.10.2) 185 | diff-lcs (>= 1.2.0, < 2.0) 186 | rspec-support (~> 3.10.0) 187 | rspec-rails (4.0.2) 188 | actionpack (>= 4.2) 189 | activesupport (>= 4.2) 190 | railties (>= 4.2) 191 | rspec-core (~> 3.10) 192 | rspec-expectations (~> 3.10) 193 | rspec-mocks (~> 3.10) 194 | rspec-support (~> 3.10) 195 | rspec-support (3.10.2) 196 | rswag-api (2.4.0) 197 | railties (>= 3.1, < 7.0) 198 | rswag-specs (2.3.1) 199 | activesupport (>= 3.1, < 7.0) 200 | json-schema (~> 2.2) 201 | railties (>= 3.1, < 7.0) 202 | rubocop (0.84.0) 203 | parallel (~> 1.10) 204 | parser (>= 2.7.0.1) 205 | rainbow (>= 2.2.2, < 4.0) 206 | rexml 207 | rubocop-ast (>= 0.0.3) 208 | ruby-progressbar (~> 1.7) 209 | unicode-display_width (>= 1.4.0, < 2.0) 210 | rubocop-ast (0.0.3) 211 | parser (>= 2.7.0.1) 212 | rubocop-performance (1.5.1) 213 | rubocop (>= 0.71.0) 214 | rubocop-rails (2.5.2) 215 | activesupport 216 | rack (>= 1.1) 217 | rubocop (>= 0.72.0) 218 | rubocop-thread_safety (0.3.4) 219 | rubocop (>= 0.51.0) 220 | ruby-progressbar (1.10.1) 221 | spring (2.1.0) 222 | spring-watcher-listen (2.0.1) 223 | listen (>= 2.7, < 4.0) 224 | spring (>= 1.2, < 3.0) 225 | sprockets (4.0.0) 226 | concurrent-ruby (~> 1.0) 227 | rack (> 1, < 3) 228 | sprockets-rails (3.2.1) 229 | actionpack (>= 4.0) 230 | activesupport (>= 4.0) 231 | sprockets (>= 3.0.0) 232 | thor (1.1.0) 233 | thread_safe (0.3.6) 234 | tzinfo (1.2.9) 235 | thread_safe (~> 0.1) 236 | unicode-display_width (1.7.0) 237 | websocket-driver (0.7.2) 238 | websocket-extensions (>= 0.1.0) 239 | websocket-extensions (0.1.5) 240 | zeitwerk (2.4.2) 241 | 242 | PLATFORMS 243 | ruby 244 | 245 | DEPENDENCIES 246 | bcrypt 247 | bootsnap (>= 1.1.0) 248 | database_cleaner 249 | dotenv-rails 250 | draper 251 | factory_bot_rails 252 | ffaker 253 | listen (>= 3.0.5, < 3.5) 254 | pagy 255 | pg (>= 0.18, < 2.0) 256 | pry-rails 257 | puma (~> 4.3) 258 | pundit 259 | rack-cors 260 | rails (~> 6.0.3) 261 | rspec-rails 262 | rswag-api 263 | rswag-specs 264 | rubocop 265 | rubocop-performance 266 | rubocop-rails 267 | rubocop-thread_safety 268 | spring 269 | spring-watcher-listen (~> 2.0.0) 270 | 271 | RUBY VERSION 272 | ruby 2.6.2p47 273 | 274 | BUNDLED WITH 275 | 1.17.2 276 | --------------------------------------------------------------------------------