├── .dockerignore ├── .env.example ├── .env.test ├── .gitattributes ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .rubocop.yml ├── .ruby-version ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── Procfile.dev ├── README.md ├── Rakefile ├── app ├── assets │ ├── builds │ │ └── .keep │ ├── config │ │ └── manifest.js │ ├── images │ │ └── .keep │ └── stylesheets │ │ ├── application.css │ │ └── application.tailwind.css ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── constraints │ └── app_domain_constraint.rb ├── controllers │ ├── application_controller.rb │ ├── concerns │ │ └── .keep │ ├── pages_controller.rb │ └── public_pages_controller.rb ├── helpers │ ├── application_helper.rb │ └── pages_helper.rb ├── javascript │ ├── application.js │ └── controllers │ │ ├── alert_controller.js │ │ ├── application.js │ │ ├── autosize_controller.js │ │ └── index.js ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ └── page.rb ├── services │ └── approximated.rb ├── validators │ └── custom_domain_validator.rb └── views │ ├── layouts │ ├── application.html.erb │ ├── mailer.html.erb │ ├── mailer.text.erb │ └── public.html.erb │ ├── pages │ ├── _form.html.erb │ ├── edit.html.erb │ ├── index.html.erb │ ├── new.html.erb │ └── show.html.erb │ ├── public_pages │ └── show.html.erb │ └── shared │ ├── _alerts.html.erb │ └── _error_messages.html.erb ├── bin ├── dev ├── docker-entrypoint ├── importmap ├── rails ├── rake └── setup ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── importmap.rb ├── initializers │ ├── assets.rb │ ├── content_security_policy.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── permissions_policy.rb │ └── public_suffix.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb ├── storage.yml └── tailwind.config.js ├── db ├── migrate │ └── 20230721090602_create_pages.rb ├── schema.rb └── seeds.rb ├── lib ├── assets │ └── .keep └── tasks │ └── .keep ├── log └── .keep ├── public ├── 404.html ├── 422.html ├── 500.html ├── apple-touch-icon-precomposed.png ├── apple-touch-icon.png ├── favicon.ico └── robots.txt ├── storage └── .keep ├── test ├── application_system_test_case.rb ├── channels │ └── application_cable │ │ └── connection_test.rb ├── controllers │ ├── .keep │ ├── pages_controller_test.rb │ └── public_pages_controller_test.rb ├── fixtures │ ├── files │ │ ├── .keep │ │ └── approximated │ │ │ ├── create.json │ │ │ ├── read.json │ │ │ └── update.json │ └── pages.yml ├── helpers │ └── .keep ├── integration │ └── .keep ├── mailers │ └── .keep ├── models │ ├── .keep │ └── page_test.rb ├── services │ └── approximated │ │ ├── creating_test.rb │ │ ├── deleting_test.rb │ │ ├── reading_test.rb │ │ └── updating_test.rb ├── support │ └── approximated_helpers.rb ├── system │ ├── .keep │ ├── pages_test.rb │ └── public_pages_test.rb └── test_helper.rb ├── tmp ├── .keep ├── pids │ └── .keep └── storage │ └── .keep └── vendor └── .keep /.dockerignore: -------------------------------------------------------------------------------- 1 | # See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. 2 | 3 | # Ignore git directory. 4 | /.git/ 5 | 6 | # Ignore bundler config. 7 | /.bundle 8 | 9 | # Ignore environment variables. 10 | /.env 11 | 12 | # Ignore all default key files. 13 | /config/master.key 14 | /config/credentials/*.key 15 | 16 | # Ignore all logfiles and tempfiles. 17 | /log/* 18 | /tmp/* 19 | !/log/.keep 20 | !/tmp/.keep 21 | 22 | # Ignore pidfiles, but keep the directory. 23 | /tmp/pids/* 24 | !/tmp/pids/ 25 | !/tmp/pids/.keep 26 | 27 | # Ignore storage (uploaded files in development and any SQLite databases). 28 | /storage/* 29 | !/storage/.keep 30 | /tmp/storage/* 31 | !/tmp/storage/ 32 | !/tmp/storage/.keep 33 | 34 | # Ignore assets. 35 | /node_modules/ 36 | /app/assets/builds/* 37 | !/app/assets/builds/.keep 38 | /public/assets 39 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | APP_PRIMARY_DOMAIN="example.com" 2 | APPROXIMATED_API_KEY="xxx" 3 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | APP_PRIMARY_DOMAIN="example.com" 2 | APPROXIMATED_API_KEY="APX-API-KEY" 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # See https://git-scm.com/docs/gitattributes for more about git attribute files. 2 | 3 | # Mark the database schema as having been generated. 4 | db/schema.rb linguist-generated 5 | 6 | # Mark any vendored files as having been vendored. 7 | vendor/* linguist-vendored 8 | config/credentials/*.yml.enc diff=rails_credentials 9 | config/credentials.yml.enc diff=rails_credentials 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | test: 11 | name: Test 12 | 13 | runs-on: ubuntu-latest 14 | timeout-minutes: 10 15 | 16 | steps: 17 | - name: Check out code 18 | uses: actions/checkout@v3 19 | 20 | - name: Set up Ruby 21 | uses: ruby/setup-ruby@v1 22 | with: 23 | bundler-cache: true 24 | 25 | - name: Run rubocop 26 | run: bundle exec rubocop --parallel 27 | 28 | - name: Set up database 29 | run: bundle exec rails db:setup 30 | env: 31 | RAILS_ENV: test 32 | 33 | - name: Run tests 34 | run: bundle exec rails test:all 35 | env: 36 | RAILS_ENV: test 37 | -------------------------------------------------------------------------------- /.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 environment variables. 11 | /.env 12 | 13 | # Ignore all default key files. 14 | /config/master.key 15 | /config/credentials/*.key 16 | 17 | # Ignore all logfiles and tempfiles. 18 | /log/* 19 | /tmp/* 20 | !/log/.keep 21 | !/tmp/.keep 22 | 23 | # Ignore pidfiles, but keep the directory. 24 | /tmp/pids/* 25 | !/tmp/pids/ 26 | !/tmp/pids/.keep 27 | 28 | # Ignore storage (uploaded files in development and any SQLite databases). 29 | /storage/* 30 | !/storage/.keep 31 | /tmp/storage/* 32 | !/tmp/storage/ 33 | !/tmp/storage/.keep 34 | 35 | # Ignore assets. 36 | /node_modules/ 37 | /app/assets/builds/* 38 | !/app/assets/builds/.keep 39 | /public/assets 40 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | require: 2 | - rubocop-rails 3 | - rubocop-performance 4 | - rubocop-minitest 5 | - rubocop-capybara 6 | 7 | AllCops: 8 | NewCops: enable 9 | 10 | Minitest/MultipleAssertions: 11 | Enabled: false 12 | 13 | Metrics: 14 | Enabled: false 15 | 16 | Rails/I18nLocaleTexts: 17 | Enabled: false 18 | 19 | Style/Documentation: 20 | Enabled: false 21 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-3.2.2 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax = docker/dockerfile:1 2 | 3 | # Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile 4 | ARG RUBY_VERSION=3.2.2 5 | FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base 6 | 7 | # Rails app lives here 8 | WORKDIR /rails 9 | 10 | # Set production environment 11 | ENV RAILS_ENV="production" \ 12 | BUNDLE_DEPLOYMENT="1" \ 13 | BUNDLE_PATH="/usr/local/bundle" \ 14 | BUNDLE_WITHOUT="development test" 15 | 16 | 17 | # Throw-away build stage to reduce size of final image 18 | FROM base as build 19 | 20 | # Install packages needed to build gems 21 | RUN apt-get update -qq && \ 22 | apt-get install --no-install-recommends -y build-essential git libvips pkg-config 23 | 24 | # Install application gems 25 | COPY Gemfile Gemfile.lock ./ 26 | RUN bundle install && \ 27 | rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ 28 | bundle exec bootsnap precompile --gemfile 29 | 30 | # Copy application code 31 | COPY . . 32 | 33 | # Precompile bootsnap code for faster boot times 34 | RUN bundle exec bootsnap precompile app/ lib/ 35 | 36 | # Precompiling assets for production without requiring secret RAILS_MASTER_KEY 37 | RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile 38 | 39 | 40 | # Final stage for app image 41 | FROM base 42 | 43 | # Install packages needed for deployment 44 | RUN apt-get update -qq && \ 45 | apt-get install --no-install-recommends -y curl libsqlite3-0 libvips && \ 46 | rm -rf /var/lib/apt/lists /var/cache/apt/archives 47 | 48 | # Copy built artifacts: gems, application 49 | COPY --from=build /usr/local/bundle /usr/local/bundle 50 | COPY --from=build /rails /rails 51 | 52 | # Run and own only the runtime files as a non-root user for security 53 | RUN useradd rails --create-home --shell /bin/bash && \ 54 | chown -R rails:rails db log storage tmp 55 | USER rails:rails 56 | 57 | # Entrypoint prepares the database. 58 | ENTRYPOINT ["/rails/bin/docker-entrypoint"] 59 | 60 | # Start the server by default, this can be overwritten at runtime 61 | EXPOSE 3000 62 | CMD ["./bin/rails", "server"] 63 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | 5 | ruby '3.2.2' 6 | 7 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 8 | gem 'rails', '~> 7.1.0' 9 | 10 | # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] 11 | gem 'sprockets-rails' 12 | 13 | # Use sqlite3 as the database for Active Record 14 | gem 'sqlite3' 15 | 16 | # Use the Puma web server [https://github.com/puma/puma] 17 | gem 'puma' 18 | 19 | # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] 20 | gem 'importmap-rails' 21 | 22 | # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] 23 | gem 'turbo-rails' 24 | 25 | # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] 26 | gem 'stimulus-rails' 27 | 28 | # Build JSON APIs with ease [https://github.com/rails/jbuilder] 29 | gem 'jbuilder' 30 | 31 | # Use Redis adapter to run Action Cable in production 32 | gem 'redis' 33 | 34 | # Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] 35 | # gem 'kredis' 36 | 37 | # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] 38 | # gem 'bcrypt' 39 | 40 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 41 | gem 'tzinfo-data', platforms: %i[windows jruby] 42 | 43 | # Reduces boot times through caching; required in config/boot.rb 44 | gem 'bootsnap', require: false 45 | 46 | # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] 47 | # gem 'image_processing' 48 | 49 | # Tailwind CSS for style 50 | gem 'tailwindcss-rails' 51 | 52 | # Custom domain validation 53 | gem 'public_suffix' 54 | 55 | # HTTP client library 56 | gem 'faraday' 57 | 58 | group :development, :test do 59 | # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem 60 | gem 'debug', platforms: %i[mri windows] 61 | 62 | # Environment variables 63 | gem 'dotenv-rails' 64 | end 65 | 66 | group :development do 67 | # Use console on exceptions pages [https://github.com/rails/web-console] 68 | gem 'web-console' 69 | 70 | # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] 71 | # gem 'rack-mini-profiler' 72 | 73 | # Speed up commands on slow machines / big apps [https://github.com/rails/spring] 74 | # gem 'spring' 75 | 76 | # Linters 77 | gem 'rubocop', require: false 78 | gem 'rubocop-capybara', require: false 79 | gem 'rubocop-minitest', require: false 80 | gem 'rubocop-performance', require: false 81 | gem 'rubocop-rails', require: false 82 | end 83 | 84 | group :test do 85 | # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] 86 | gem 'capybara' 87 | gem 'cuprite' 88 | gem 'webmock' 89 | end 90 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (7.1.1) 5 | actionpack (= 7.1.1) 6 | activesupport (= 7.1.1) 7 | nio4r (~> 2.0) 8 | websocket-driver (>= 0.6.1) 9 | zeitwerk (~> 2.6) 10 | actionmailbox (7.1.1) 11 | actionpack (= 7.1.1) 12 | activejob (= 7.1.1) 13 | activerecord (= 7.1.1) 14 | activestorage (= 7.1.1) 15 | activesupport (= 7.1.1) 16 | mail (>= 2.7.1) 17 | net-imap 18 | net-pop 19 | net-smtp 20 | actionmailer (7.1.1) 21 | actionpack (= 7.1.1) 22 | actionview (= 7.1.1) 23 | activejob (= 7.1.1) 24 | activesupport (= 7.1.1) 25 | mail (~> 2.5, >= 2.5.4) 26 | net-imap 27 | net-pop 28 | net-smtp 29 | rails-dom-testing (~> 2.2) 30 | actionpack (7.1.1) 31 | actionview (= 7.1.1) 32 | activesupport (= 7.1.1) 33 | nokogiri (>= 1.8.5) 34 | rack (>= 2.2.4) 35 | rack-session (>= 1.0.1) 36 | rack-test (>= 0.6.3) 37 | rails-dom-testing (~> 2.2) 38 | rails-html-sanitizer (~> 1.6) 39 | actiontext (7.1.1) 40 | actionpack (= 7.1.1) 41 | activerecord (= 7.1.1) 42 | activestorage (= 7.1.1) 43 | activesupport (= 7.1.1) 44 | globalid (>= 0.6.0) 45 | nokogiri (>= 1.8.5) 46 | actionview (7.1.1) 47 | activesupport (= 7.1.1) 48 | builder (~> 3.1) 49 | erubi (~> 1.11) 50 | rails-dom-testing (~> 2.2) 51 | rails-html-sanitizer (~> 1.6) 52 | activejob (7.1.1) 53 | activesupport (= 7.1.1) 54 | globalid (>= 0.3.6) 55 | activemodel (7.1.1) 56 | activesupport (= 7.1.1) 57 | activerecord (7.1.1) 58 | activemodel (= 7.1.1) 59 | activesupport (= 7.1.1) 60 | timeout (>= 0.4.0) 61 | activestorage (7.1.1) 62 | actionpack (= 7.1.1) 63 | activejob (= 7.1.1) 64 | activerecord (= 7.1.1) 65 | activesupport (= 7.1.1) 66 | marcel (~> 1.0) 67 | activesupport (7.1.1) 68 | base64 69 | bigdecimal 70 | concurrent-ruby (~> 1.0, >= 1.0.2) 71 | connection_pool (>= 2.2.5) 72 | drb 73 | i18n (>= 1.6, < 2) 74 | minitest (>= 5.1) 75 | mutex_m 76 | tzinfo (~> 2.0) 77 | addressable (2.8.5) 78 | public_suffix (>= 2.0.2, < 6.0) 79 | ast (2.4.2) 80 | base64 (0.1.1) 81 | bigdecimal (3.1.4) 82 | bindex (0.8.1) 83 | bootsnap (1.16.0) 84 | msgpack (~> 1.2) 85 | builder (3.2.4) 86 | capybara (3.39.2) 87 | addressable 88 | matrix 89 | mini_mime (>= 0.1.3) 90 | nokogiri (~> 1.8) 91 | rack (>= 1.6.0) 92 | rack-test (>= 0.6.3) 93 | regexp_parser (>= 1.5, < 3.0) 94 | xpath (~> 3.2) 95 | concurrent-ruby (1.2.2) 96 | connection_pool (2.4.1) 97 | crack (0.4.5) 98 | rexml 99 | crass (1.0.6) 100 | cuprite (0.14.3) 101 | capybara (~> 3.0) 102 | ferrum (~> 0.13.0) 103 | date (3.3.3) 104 | debug (1.8.0) 105 | irb (>= 1.5.0) 106 | reline (>= 0.3.1) 107 | dotenv (2.8.1) 108 | dotenv-rails (2.8.1) 109 | dotenv (= 2.8.1) 110 | railties (>= 3.2) 111 | drb (2.1.1) 112 | ruby2_keywords 113 | erubi (1.12.0) 114 | faraday (2.7.11) 115 | base64 116 | faraday-net_http (>= 2.0, < 3.1) 117 | ruby2_keywords (>= 0.0.4) 118 | faraday-net_http (3.0.2) 119 | ferrum (0.13) 120 | addressable (~> 2.5) 121 | concurrent-ruby (~> 1.1) 122 | webrick (~> 1.7) 123 | websocket-driver (>= 0.6, < 0.8) 124 | globalid (1.2.1) 125 | activesupport (>= 6.1) 126 | hashdiff (1.0.1) 127 | i18n (1.14.1) 128 | concurrent-ruby (~> 1.0) 129 | importmap-rails (1.2.1) 130 | actionpack (>= 6.0.0) 131 | railties (>= 6.0.0) 132 | io-console (0.6.0) 133 | irb (1.8.1) 134 | rdoc 135 | reline (>= 0.3.8) 136 | jbuilder (2.11.5) 137 | actionview (>= 5.0.0) 138 | activesupport (>= 5.0.0) 139 | json (2.6.3) 140 | language_server-protocol (3.17.0.3) 141 | loofah (2.21.4) 142 | crass (~> 1.0.2) 143 | nokogiri (>= 1.12.0) 144 | mail (2.8.1) 145 | mini_mime (>= 0.1.1) 146 | net-imap 147 | net-pop 148 | net-smtp 149 | marcel (1.0.2) 150 | matrix (0.4.2) 151 | mini_mime (1.1.5) 152 | minitest (5.20.0) 153 | msgpack (1.7.2) 154 | mutex_m (0.1.2) 155 | net-imap (0.4.1) 156 | date 157 | net-protocol 158 | net-pop (0.1.2) 159 | net-protocol 160 | net-protocol (0.2.1) 161 | timeout 162 | net-smtp (0.4.0) 163 | net-protocol 164 | nio4r (2.5.9) 165 | nokogiri (1.15.4-x86_64-darwin) 166 | racc (~> 1.4) 167 | nokogiri (1.15.4-x86_64-linux) 168 | racc (~> 1.4) 169 | parallel (1.23.0) 170 | parser (3.2.2.4) 171 | ast (~> 2.4.1) 172 | racc 173 | psych (5.1.1) 174 | stringio 175 | public_suffix (5.0.3) 176 | puma (6.4.0) 177 | nio4r (~> 2.0) 178 | racc (1.7.1) 179 | rack (3.0.8) 180 | rack-session (2.0.0) 181 | rack (>= 3.0.0) 182 | rack-test (2.1.0) 183 | rack (>= 1.3) 184 | rackup (2.1.0) 185 | rack (>= 3) 186 | webrick (~> 1.8) 187 | rails (7.1.1) 188 | actioncable (= 7.1.1) 189 | actionmailbox (= 7.1.1) 190 | actionmailer (= 7.1.1) 191 | actionpack (= 7.1.1) 192 | actiontext (= 7.1.1) 193 | actionview (= 7.1.1) 194 | activejob (= 7.1.1) 195 | activemodel (= 7.1.1) 196 | activerecord (= 7.1.1) 197 | activestorage (= 7.1.1) 198 | activesupport (= 7.1.1) 199 | bundler (>= 1.15.0) 200 | railties (= 7.1.1) 201 | rails-dom-testing (2.2.0) 202 | activesupport (>= 5.0.0) 203 | minitest 204 | nokogiri (>= 1.6) 205 | rails-html-sanitizer (1.6.0) 206 | loofah (~> 2.21) 207 | nokogiri (~> 1.14) 208 | railties (7.1.1) 209 | actionpack (= 7.1.1) 210 | activesupport (= 7.1.1) 211 | irb 212 | rackup (>= 1.0.0) 213 | rake (>= 12.2) 214 | thor (~> 1.0, >= 1.2.2) 215 | zeitwerk (~> 2.6) 216 | rainbow (3.1.1) 217 | rake (13.0.6) 218 | rdoc (6.5.0) 219 | psych (>= 4.0.0) 220 | redis (5.0.7) 221 | redis-client (>= 0.9.0) 222 | redis-client (0.17.0) 223 | connection_pool 224 | regexp_parser (2.8.2) 225 | reline (0.3.9) 226 | io-console (~> 0.5) 227 | rexml (3.2.6) 228 | rubocop (1.57.0) 229 | base64 (~> 0.1.1) 230 | json (~> 2.3) 231 | language_server-protocol (>= 3.17.0) 232 | parallel (~> 1.10) 233 | parser (>= 3.2.2.4) 234 | rainbow (>= 2.2.2, < 4.0) 235 | regexp_parser (>= 1.8, < 3.0) 236 | rexml (>= 3.2.5, < 4.0) 237 | rubocop-ast (>= 1.28.1, < 2.0) 238 | ruby-progressbar (~> 1.7) 239 | unicode-display_width (>= 2.4.0, < 3.0) 240 | rubocop-ast (1.29.0) 241 | parser (>= 3.2.1.0) 242 | rubocop-capybara (2.19.0) 243 | rubocop (~> 1.41) 244 | rubocop-minitest (0.32.2) 245 | rubocop (>= 1.39, < 2.0) 246 | rubocop-performance (1.19.1) 247 | rubocop (>= 1.7.0, < 2.0) 248 | rubocop-ast (>= 0.4.0) 249 | rubocop-rails (2.21.2) 250 | activesupport (>= 4.2.0) 251 | rack (>= 1.1) 252 | rubocop (>= 1.33.0, < 2.0) 253 | ruby-progressbar (1.13.0) 254 | ruby2_keywords (0.0.5) 255 | sprockets (4.2.1) 256 | concurrent-ruby (~> 1.0) 257 | rack (>= 2.2.4, < 4) 258 | sprockets-rails (3.4.2) 259 | actionpack (>= 5.2) 260 | activesupport (>= 5.2) 261 | sprockets (>= 3.0.0) 262 | sqlite3 (1.6.7-x86_64-darwin) 263 | sqlite3 (1.6.7-x86_64-linux) 264 | stimulus-rails (1.3.0) 265 | railties (>= 6.0.0) 266 | stringio (3.0.8) 267 | tailwindcss-rails (2.0.31-x86_64-darwin) 268 | railties (>= 6.0.0) 269 | tailwindcss-rails (2.0.31-x86_64-linux) 270 | railties (>= 6.0.0) 271 | thor (1.2.2) 272 | timeout (0.4.0) 273 | turbo-rails (1.5.0) 274 | actionpack (>= 6.0.0) 275 | activejob (>= 6.0.0) 276 | railties (>= 6.0.0) 277 | tzinfo (2.0.6) 278 | concurrent-ruby (~> 1.0) 279 | unicode-display_width (2.5.0) 280 | web-console (4.2.1) 281 | actionview (>= 6.0.0) 282 | activemodel (>= 6.0.0) 283 | bindex (>= 0.4.0) 284 | railties (>= 6.0.0) 285 | webmock (3.19.1) 286 | addressable (>= 2.8.0) 287 | crack (>= 0.3.2) 288 | hashdiff (>= 0.4.0, < 2.0.0) 289 | webrick (1.8.1) 290 | websocket-driver (0.7.6) 291 | websocket-extensions (>= 0.1.0) 292 | websocket-extensions (0.1.5) 293 | xpath (3.2.0) 294 | nokogiri (~> 1.8) 295 | zeitwerk (2.6.12) 296 | 297 | PLATFORMS 298 | x86_64-darwin-22 299 | x86_64-linux 300 | 301 | DEPENDENCIES 302 | bootsnap 303 | capybara 304 | cuprite 305 | debug 306 | dotenv-rails 307 | faraday 308 | importmap-rails 309 | jbuilder 310 | public_suffix 311 | puma 312 | rails (~> 7.1.0) 313 | redis 314 | rubocop 315 | rubocop-capybara 316 | rubocop-minitest 317 | rubocop-performance 318 | rubocop-rails 319 | sprockets-rails 320 | sqlite3 321 | stimulus-rails 322 | tailwindcss-rails 323 | turbo-rails 324 | tzinfo-data 325 | web-console 326 | webmock 327 | 328 | RUBY VERSION 329 | ruby 3.2.2p53 330 | 331 | BUNDLED WITH 332 | 2.4.10 333 | -------------------------------------------------------------------------------- /Procfile.dev: -------------------------------------------------------------------------------- 1 | web: bin/rails server -p 3000 2 | css: bin/rails tailwindcss:watch 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rails Custom Domains Example 2 | 3 | This is an example repo to help you understand how you could implement custom domains easily as a feature 4 | in your Rails application using [Approximated](https://approximated.app). 5 | 6 | 7 | ## How it works 8 | 9 | The core unit of this application is a Page model. It consists of a title, a simple textual content, and a custom 10 | domain. The application provides a simple user interface to manage these Pages, syncs the changes to Approximated 11 | and displays the Page on the specified custom domain. 12 | 13 | When a Page with a custom domain is created, the application will create a virtual host in Approximated and provide 14 | instructions to set a DNS record for the domain. When a Page is changed, it'll update the virtual host and when 15 | it's destroyed, it'll delete the virtual host. 16 | 17 | The flow of an incoming request is as follows: 18 | - The request hits the router. 19 | - The router checks if the requested domain matches the application primary domain specified as an env variable 20 | `APP_PRIMARY_DOMAIN`. 21 | - If the requested domain matches the application domain, it routes the request to the `PagesController` 22 | and shows the management of Pages. 23 | - If it doesn't match the application domain, it routes the request to the `PublicPagesController`. 24 | - The `PublicPagesController` tries to find a Page with the requested custom domain based on either 25 | the request header `apx-incoming-host` or the request host. 26 | - If a Page with this custom domain is found, it'll render the public site for the Page. 27 | - If the requested domain doesn't match a custom domain in the database or the primary domain, it shows 404. 28 | 29 | 30 | ## Files to check out 31 | 32 | - [config/routes.rb](config/routes.rb) - 33 | Rails routing for the main application and public pages with custom domains. 34 | - [app/constraints/app_domain_constraint.rb](app/constraints/app_domain_constraint.rb) - 35 | Route constraint to differentiate between primary domain and custom domains. 36 | - [app/controllers/pages_controller.rb](app/controllers/pages_controller.rb) - 37 | Controller for managing pages. 38 | - [app/controllers/public_pages_controller.rb](app/controllers/public_pages_controller.rb) - 39 | Controller handling custom domains. 40 | - [app/models/page.rb](app/models/page.rb) - 41 | Page model with callbacks managing Approximated virtual hosts. 42 | - [app/services/approximated.rb](app/services/approximated.rb) - 43 | Service for talking to the Approximated API. 44 | - [app/views/layouts/application.html.erb](app/views/layouts/application.html.erb) - 45 | View layout for main application. 46 | - [app/views/layouts/public.html.erb](app/views/layouts/public.html.erb) - 47 | View layout for public pages on custom domains. 48 | 49 | 50 | ## Trying it out 51 | 52 | 1. Copy the `.env.example` file to `.env`. 53 | 2. Set the `APP_PRIMARY_DOMAIN` in `.env` to your local dev domain (e.g. `localhost`). 54 | 3. Set the `APPROXIMATED_API_KEY` in `.env` to your API key from the Approximated dashboard. 55 | 4. Run `bundle install`, `bin/rails db:setup` and `bin/dev` from the project root folder. 56 | 5. Open the application in your browser and create a Page. Fill in your local domain 57 | (e.g. `localhost`) as a custom domain. 58 | 6. To test the custom domain in a local environment, change the `APP_PRIMARY_DOMAIN` in the `.env` file 59 | to anything else temporarily. This makes the router not match your local domain as the primary domain, 60 | so it'll handle it as a custom domain. 61 | 7. Restart the web server and reload the page. You should see a public site for your Page. 62 | 8. To get back to the main app dashboard again, just change the `APP_PRIMARY_DOMAIN` back. 63 | 64 | 65 | ## Assets and CORS 66 | 67 | These work out of the box in this example app, because their paths are relative. If your app is linking 68 | to assets with absolute URLs, changing them to relative paths should fix any CORS issues. 69 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/assets/builds/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/app/assets/builds/.keep -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../stylesheets .css 3 | //= link_tree ../../javascript .js 4 | //= link_tree ../builds 5 | -------------------------------------------------------------------------------- /app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/app/assets/images/.keep -------------------------------------------------------------------------------- /app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's 6 | * vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /app/assets/stylesheets/application.tailwind.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | @layer components { 6 | .alert { 7 | @apply relative border px-4 py-3 mb-6 rounded; 8 | } 9 | 10 | .alert-dismissible { 11 | @apply pr-10; 12 | } 13 | 14 | .alert-close { 15 | @apply absolute top-0 right-0 px-4 py-3; 16 | } 17 | 18 | .alert-red { 19 | @apply bg-red-100 border-red-400 text-red-700; 20 | } 21 | 22 | .alert-blue { 23 | @apply bg-blue-100 border-blue-400 text-blue-700; 24 | } 25 | 26 | .btn { 27 | @apply inline-block rounded-md px-3 py-2 text-sm font-semibold ring-1 ring-inset 28 | focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2; 29 | } 30 | 31 | .btn-primary { 32 | @apply bg-blue-600 text-white ring-transparent focus-visible:outline-blue-600 hover:bg-blue-500; 33 | } 34 | 35 | .btn-danger { 36 | @apply bg-red-600 text-white ring-transparent focus-visible:outline-red-600 hover:bg-red-500; 37 | } 38 | 39 | .btn-secondary { 40 | @apply bg-white text-gray-900 ring-gray-300 focus-visible:outline-gray-500 hover:bg-gray-100; 41 | } 42 | 43 | .form-group { 44 | @apply block w-full mb-4; 45 | } 46 | 47 | .form-label { 48 | @apply block w-full mb-1; 49 | } 50 | 51 | .field_with_errors .form-label { 52 | @apply text-red-600; 53 | } 54 | 55 | .form-field { 56 | @apply block leading-tight w-full mb-1 py-2 px-3 bg-white rounded border 57 | border-gray-300 focus:outline-none focus:ring focus:ring-blue-300 58 | disabled:bg-gray-100 disabled:text-gray-600 disabled:cursor-default; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /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/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/constraints/app_domain_constraint.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class AppDomainConstraint 4 | def self.matches?(request) 5 | requested_host = request.headers['apx-incoming-host'].presence || request.host 6 | requested_host.blank? || requested_host == ENV.fetch('APP_PRIMARY_DOMAIN') 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::Base 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/pages_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class PagesController < ApplicationController 4 | def index 5 | @pages = Page.all 6 | end 7 | 8 | def show 9 | @page = Page.find(params[:id]) 10 | end 11 | 12 | def new 13 | @page = Page.new 14 | end 15 | 16 | def edit 17 | @page = Page.find(params[:id]) 18 | end 19 | 20 | def create 21 | @page = Page.new(page_params) 22 | 23 | if @page.save 24 | message = @page.user_message || 'Page was successfully created.' 25 | redirect_to page_path(@page), notice: message 26 | else 27 | render :new, status: :unprocessable_entity 28 | end 29 | end 30 | 31 | def update 32 | @page = Page.find(params[:id]) 33 | 34 | if @page.update(page_params) 35 | message = @page.user_message || 'Page was successfully updated.' 36 | redirect_to page_path(@page), notice: message 37 | else 38 | render :edit, status: :unprocessable_entity 39 | end 40 | end 41 | 42 | def destroy 43 | @page = Page.find(params[:id]) 44 | 45 | if @page.destroy 46 | message = @page.user_message || 'Page was successfully destroyed.' 47 | redirect_to pages_root_path, notice: message 48 | else 49 | render :show, status: :unprocessable_entity 50 | end 51 | end 52 | 53 | private 54 | 55 | def page_params 56 | params.require(:page).permit(:title, :content, :domain) 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /app/controllers/public_pages_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class PublicPagesController < ApplicationController 4 | layout 'public' 5 | 6 | def show 7 | @page = Page.find_by!(domain: requested_host) 8 | end 9 | 10 | private 11 | 12 | def requested_host 13 | request.headers['apx-incoming-host'].presence || request.host 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationHelper 4 | end 5 | -------------------------------------------------------------------------------- /app/helpers/pages_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module PagesHelper 4 | end 5 | -------------------------------------------------------------------------------- /app/javascript/application.js: -------------------------------------------------------------------------------- 1 | // Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails 2 | import "@hotwired/turbo-rails" 3 | import "controllers" 4 | -------------------------------------------------------------------------------- /app/javascript/controllers/alert_controller.js: -------------------------------------------------------------------------------- 1 | import { Controller } from "@hotwired/stimulus" 2 | 3 | export default class extends Controller { 4 | static targets = ["alert"] 5 | 6 | dismiss(event) { 7 | event.preventDefault() 8 | this.alertTarget.parentElement.removeChild(this.alertTarget) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/javascript/controllers/application.js: -------------------------------------------------------------------------------- 1 | import { Application } from "@hotwired/stimulus" 2 | 3 | const application = Application.start() 4 | 5 | // Configure Stimulus development experience 6 | application.debug = false 7 | window.Stimulus = application 8 | 9 | export { application } 10 | -------------------------------------------------------------------------------- /app/javascript/controllers/autosize_controller.js: -------------------------------------------------------------------------------- 1 | import { Controller } from "@hotwired/stimulus" 2 | import autosize from "autosize" 3 | 4 | export default class extends Controller { 5 | connect() { 6 | autosize(this.element) 7 | } 8 | 9 | disconnect() { 10 | autosize.destroy(this.element) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/javascript/controllers/index.js: -------------------------------------------------------------------------------- 1 | // Import and register all your controllers from the importmap under controllers/* 2 | 3 | import { application } from "controllers/application" 4 | 5 | // Eager load all controllers defined in the import map under controllers/**/*_controller 6 | import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" 7 | eagerLoadControllersFrom("controllers", application) 8 | 9 | // Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) 10 | // import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" 11 | // lazyLoadControllersFrom("controllers", application) 12 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationJob < ActiveJob::Base 4 | # Automatically retry jobs that encountered a deadlock 5 | # retry_on ActiveRecord::Deadlocked 6 | 7 | # Most jobs are safe to ignore if the underlying records are no longer available 8 | # discard_on ActiveJob::DeserializationError 9 | end 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationRecord < ActiveRecord::Base 4 | primary_abstract_class 5 | end 6 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/page.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Page < ApplicationRecord 4 | attribute :user_message, :text 5 | 6 | validates :title, presence: true 7 | validates :content, presence: true 8 | validates :domain, presence: true, uniqueness: true, custom_domain: true 9 | 10 | after_create :create_apx_vhost 11 | after_update :update_apx_vhost 12 | after_destroy :destroy_apx_vhost 13 | 14 | private 15 | 16 | def create_apx_vhost 17 | apx = Approximated.new 18 | rollback_on_apx_error do 19 | result = apx.create_vhost(domain, ENV.fetch('APP_PRIMARY_DOMAIN')) 20 | self.user_message = result.body.dig('data', 'user_message').presence 21 | end 22 | end 23 | 24 | def update_apx_vhost 25 | return unless domain_previously_changed? 26 | 27 | apx = Approximated.new 28 | rollback_on_apx_error do 29 | apx.get_vhost(domain_previously_was) 30 | apx.update_vhost(domain_previously_was, 'incoming_address' => domain) 31 | rescue Approximated::ResourceNotFound 32 | apx.create_vhost(domain, ENV.fetch('APP_PRIMARY_DOMAIN')) 33 | end 34 | end 35 | 36 | def destroy_apx_vhost 37 | apx = Approximated.new 38 | rollback_on_apx_error do 39 | apx.delete_vhost(domain) 40 | rescue Approximated::ResourceNotFound 41 | # Ignore missing vhost 42 | end 43 | end 44 | 45 | def rollback_on_apx_error 46 | yield 47 | rescue Approximated::Error => e 48 | errors.add(:base, "APX Error: #{e.cause.to_s.upcase_first}") 49 | raise ActiveRecord::Rollback 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /app/services/approximated.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Approximated is a ruby wrapper for the Approximated API (https://approximated.app). 4 | # 5 | class Approximated 6 | # Data class holding a successful API response. 7 | Result = Data.define(:status, :body) 8 | 9 | # Approximated error base class. 10 | class Error < StandardError; end 11 | 12 | # Error raised on a 404 response. 13 | class ResourceNotFound < Error; end 14 | 15 | # Error raised on a 401 response. 16 | class UnauthorizedError < Error; end 17 | 18 | # Creates a virtual host. 19 | # 20 | # @param incoming_address [String] The incoming address. 21 | # @param target_address [String] The target address. 22 | # @param options [Hash] Optional fields. See https://approximated.app/docs/#create-virtual-host for more details. 23 | # 24 | # @return [Approximated::Result] 25 | # 26 | # @raise [Approximated::UnauthorizedError] If the API key does not exist. 27 | # 28 | def create_vhost(incoming_address, target_address, options = {}) 29 | handle_exceptions do 30 | data = options.merge({ incoming_address:, target_address: }) 31 | response = connection.post('/api/vhosts', data) 32 | handle_response(response) 33 | end 34 | end 35 | 36 | # Updates a virtual host. 37 | # Any fields not passed into options will remain the same. 38 | # 39 | # @param current_incoming_address [String] The current incoming address. 40 | # @param options [Hash] Optional fields. See https://approximated.app/docs/#update-virtual-host for more details. 41 | # 42 | # @return [Approximated::Result] 43 | # 44 | # @raise [Approximated::UnauthorizedError] If the API key does not exist. 45 | # @raise [Approximated::ResourceNotFound] If the virtual host could not be found. 46 | # 47 | def update_vhost(current_incoming_address, options = {}) 48 | handle_exceptions do 49 | data = options.merge({ current_incoming_address: }) 50 | response = connection.post('/api/vhosts/update/by/incoming', data) 51 | handle_response(response) 52 | end 53 | end 54 | 55 | # Reads a virtual host. 56 | # 57 | # @param incoming_address [String] The incoming address. 58 | # 59 | # @return [Approximated::Result] 60 | # 61 | # @raise [Approximated::UnauthorizedError] If the API key does not exist. 62 | # @raise [Approximated::ResourceNotFound] If the virtual host could not be found. 63 | # 64 | def get_vhost(incoming_address) 65 | handle_exceptions do 66 | response = connection.get("/api/vhosts/by/incoming/#{incoming_address}") 67 | handle_response(response) 68 | end 69 | end 70 | 71 | # Deletes a virtual host. 72 | # 73 | # @param incoming_address [String] The incoming address. 74 | # 75 | # @return [Approximated::Result] 76 | # 77 | # @raise [Approximated::UnauthorizedError] If the API key does not exist. 78 | # @raise [Approximated::ResourceNotFound] If the virtual host could not be found. 79 | # 80 | def delete_vhost(incoming_address) 81 | handle_exceptions do 82 | response = connection.delete("/api/vhosts/by/incoming/#{incoming_address}") 83 | handle_response(response) 84 | end 85 | end 86 | 87 | private 88 | 89 | def connection 90 | @connection ||= Faraday.new( 91 | url: 'https://cloud.approximated.app/', 92 | headers: { 'api-key' => ENV.fetch('APPROXIMATED_API_KEY') } 93 | ) do |faraday| 94 | faraday.request :json 95 | faraday.response :json, preserve_raw: true 96 | faraday.response :raise_error 97 | end 98 | end 99 | 100 | def handle_response(response) 101 | Result.new(status: response.status, body: response.body) 102 | end 103 | 104 | def handle_exceptions 105 | yield 106 | rescue Faraday::UnauthorizedError 107 | raise UnauthorizedError 108 | rescue Faraday::ResourceNotFound 109 | raise ResourceNotFound 110 | rescue Faraday::Error 111 | raise Error 112 | end 113 | end 114 | -------------------------------------------------------------------------------- /app/validators/custom_domain_validator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class CustomDomainValidator < ActiveModel::EachValidator 4 | RESERVED_DOMAINS = [ENV.fetch('APP_PRIMARY_DOMAIN')].freeze 5 | 6 | def validate_each(record, attribute, value) 7 | return if value.blank? 8 | return if valid_custom_domain?(value) 9 | 10 | record.errors.add(attribute, options[:message] || :invalid) 11 | end 12 | 13 | private 14 | 15 | def valid_custom_domain?(value) 16 | return false if RESERVED_DOMAINS.include?(value.downcase) 17 | 18 | # Strictly validate domain (without the default "*" rule) 19 | return false unless PublicSuffix.valid?(value, default_rule: nil) 20 | 21 | true 22 | rescue PublicSuffixService::DomainNotAllowed 23 | false 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Approximated Example App 8 | 9 | 10 | 11 | <%= csrf_meta_tags %> 12 | <%= csp_meta_tag %> 13 | 14 | <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %> 15 | <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> 16 | 17 | <%= javascript_importmap_tags %> 18 | 19 | 20 | 21 |
22 | <%= render "shared/alerts" %> 23 | <%= yield %> 24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/views/layouts/public.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | <%= @page.title %> 8 | 9 | 10 | 11 | <%= csrf_meta_tags %> 12 | <%= csp_meta_tag %> 13 | 14 | <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %> 15 | <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> 16 | 17 | <%= javascript_importmap_tags %> 18 | 19 | 20 | 21 |
22 | <%= render "shared/alerts" %> 23 | <%= yield %> 24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /app/views/pages/_form.html.erb: -------------------------------------------------------------------------------- 1 | <%= form_with(model: page) do |form| %> 2 | <%= render "shared/error_messages", resource: form.object %> 3 | 4 |
5 | <%= form.label :title, class: "form-label" %> 6 | <%= form.text_field :title, class: "form-field" %> 7 |
8 | 9 |
10 | <%= form.label :domain, class: "form-label" %> 11 | <%= form.text_field :domain, class: "form-field" %> 12 |
13 | 14 |
15 | <%= form.label :content, class: "form-label" %> 16 | <%= form.text_area :content, rows: 10, class: "form-field", data: { controller: "autosize" } %> 17 |
18 | 19 |
20 | <%= link_to "Cancel", page.new_record? ? pages_root_path : page_path(page), class: "btn btn-secondary" %> 21 | <%= form.submit page.new_record? ? "Create page" : "Save page", class: "btn btn-primary" %> 22 |
23 | <% end %> 24 | -------------------------------------------------------------------------------- /app/views/pages/edit.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

Edit page

3 |
4 | 5 |
6 | <%= render "form", page: @page %> 7 |
8 | -------------------------------------------------------------------------------- /app/views/pages/index.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

Pages

3 | 4 |
5 | <%= link_to "New page", new_page_path, class: "btn btn-primary" %> 6 |
7 |
8 | 9 |
10 | <% if @pages.any? %> 11 | 18 | <% else %> 19 |
20 | No pages 21 |
22 | <% end %> 23 |
24 | -------------------------------------------------------------------------------- /app/views/pages/new.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

New page

3 |
4 | 5 |
6 | <%= render "form", page: @page %> 7 |
8 | -------------------------------------------------------------------------------- /app/views/pages/show.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

<%= @page.title %>

3 |
4 | 5 |
6 | <%= render "shared/error_messages", resource: @page %> 7 | 8 |

9 | Domain: 10 | <%= link_to @page.domain, public_pages_root_url(host: @page.domain, port: nil), 11 | target: "_blank", class: "underline" %> 12 |

13 | 14 |
15 | <%= simple_format @page.content %> 16 |
17 | 18 |
19 | <%= link_to "Back to pages", pages_root_path, class: "btn btn-secondary" %> 20 | <%= link_to "Edit this page", edit_page_path(@page), class: "btn btn-primary" %> 21 | <%= link_to "Destroy this page", @page, class: "btn btn-danger", data: { 22 | turbo_confirm: "Are you sure?", turbo_method: :delete 23 | } %> 24 |
25 |
26 | -------------------------------------------------------------------------------- /app/views/public_pages/show.html.erb: -------------------------------------------------------------------------------- 1 |
2 |
3 |

<%= @page.title %>

4 |
5 | 6 |
7 | <%= simple_format @page.content %> 8 |
9 |
-------------------------------------------------------------------------------- /app/views/shared/_alerts.html.erb: -------------------------------------------------------------------------------- 1 | <% if flash.notice %> 2 |
3 | 7 |
8 | <% end %> 9 | -------------------------------------------------------------------------------- /app/views/shared/_error_messages.html.erb: -------------------------------------------------------------------------------- 1 | <% if resource.errors.any? %> 2 | 12 | <% end %> 13 | -------------------------------------------------------------------------------- /bin/dev: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | if command -v overmind &> /dev/null; then 4 | overmind start -f Procfile.dev "$@" 5 | else 6 | foreman start -f Procfile.dev "$@" 7 | fi 8 | -------------------------------------------------------------------------------- /bin/docker-entrypoint: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | # If running the rails server then create or migrate existing database 4 | if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then 5 | ./bin/rails db:prepare 6 | fi 7 | 8 | exec "${@}" 9 | -------------------------------------------------------------------------------- /bin/importmap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require_relative "../config/application" 4 | require "importmap/commands" 5 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path("../config/application", __dir__) 3 | require_relative "../config/boot" 4 | require "rails/commands" 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative "../config/boot" 3 | require "rake" 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path("..", __dir__) 6 | 7 | def system!(*args) 8 | system(*args, exception: true) 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 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 | # FileUtils.cp "config/database.yml.sample", "config/database.yml" 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! "bin/rails db:prepare" 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 | -------------------------------------------------------------------------------- /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 | Rails.application.load_server 9 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'boot' 4 | 5 | require 'rails/all' 6 | 7 | # Require the gems listed in Gemfile, including any gems 8 | # you've limited to :test, :development, or :production. 9 | Bundler.require(*Rails.groups) 10 | 11 | module ApproximatedExample 12 | class Application < Rails::Application 13 | # Initialize configuration defaults for originally generated Rails version. 14 | config.load_defaults 7.1 15 | 16 | # Please, add to the `ignore` list any other `lib` subdirectories that do 17 | # not contain `.rb` files, or that should not be reloaded or eager loaded. 18 | # Common ones are `templates`, `generators`, or `middleware`, for example. 19 | config.autoload_lib(ignore: %w[assets tasks]) 20 | 21 | # Configuration for the application, engines, and railties goes here. 22 | # 23 | # These settings can be overridden in specific environments using the files 24 | # in config/environments, which are processed later. 25 | # 26 | # config.time_zone = "Central Time (US & Canada)" 27 | # config.eager_load_paths << Rails.root.join("extras") 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: redis 3 | url: redis://localhost:6379/1 4 | 5 | test: 6 | adapter: test 7 | 8 | production: 9 | adapter: redis 10 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 11 | channel_prefix: approximated_example_production 12 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | Qq3D8zslApcSVstcb93ldwEzvKLtrhbA6CSI7NYvo7mxk6bcvHk9D1+AajZNjD1go6eZmSVUBoPbhArRynzsLxNhTfAHe4GkKJec5ob6croubEFgdrp4sk1A5Y0No3aixccyBv+KXWA1W/nq7mg20GCZsPxpCDulsr0ru3hK2Vj7IyoaBy+Hfy5CQiTDOHmwSQAVVNX2wzb+lRR1UxnumGDQ8BYtirwjBZwEwiWegoKu5l6X45xmAb+vQh37/A3Yl2Br5jsGMAF0c9424d8EsP+a0JAR2jWhB1y0dWa3bYgXD50hZuD4eBYyW0u0S247QQrTxC4Lg0EKiI1qbU+eKy0omZM6dGl4TCeI/+Zv4eZhIJgf+4R965AnIF/LZlAhLUVjGspveIV4JDO8JrcHyEiCuF33MtrZy9Pp--M9xvA63+Pro8zq20--xMqNGPkFO4p24Ck6DMHX+A== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite. Versions 3.8.0 and up are supported. 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: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: storage/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: storage/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: storage/production.sqlite3 26 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'active_support/core_ext/integer/time' 4 | 5 | Rails.application.configure do 6 | # Settings specified here will take precedence over those in config/application.rb. 7 | 8 | # In the development environment your application's code is reloaded any time 9 | # it changes. This slows down response time but is perfect for development 10 | # since you don't have to restart the web server when you make code changes. 11 | config.enable_reloading = true 12 | 13 | # Do not eager load code on boot. 14 | config.eager_load = false 15 | 16 | # Show full error reports. 17 | config.consider_all_requests_local = true 18 | 19 | # Enable server timing 20 | config.server_timing = true 21 | 22 | # Enable/disable caching. By default caching is disabled. 23 | # Run rails dev:cache to toggle caching. 24 | if Rails.root.join('tmp/caching-dev.txt').exist? 25 | config.action_controller.perform_caching = true 26 | config.action_controller.enable_fragment_cache_logging = true 27 | 28 | config.cache_store = :memory_store 29 | config.public_file_server.headers = { 30 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 31 | } 32 | else 33 | config.action_controller.perform_caching = false 34 | 35 | config.cache_store = :null_store 36 | end 37 | 38 | # Store uploaded files on the local file system (see config/storage.yml for options). 39 | config.active_storage.service = :local 40 | 41 | # Don't care if the mailer can't send. 42 | config.action_mailer.raise_delivery_errors = false 43 | 44 | config.action_mailer.perform_caching = false 45 | 46 | # Print deprecation notices to the Rails logger. 47 | config.active_support.deprecation = :log 48 | 49 | # Raise exceptions for disallowed deprecations. 50 | config.active_support.disallowed_deprecation = :raise 51 | 52 | # Tell Active Support which deprecation messages to disallow. 53 | config.active_support.disallowed_deprecation_warnings = [] 54 | 55 | # Raise an error on page load if there are pending migrations. 56 | config.active_record.migration_error = :page_load 57 | 58 | # Highlight code that triggered database queries in logs. 59 | config.active_record.verbose_query_logs = true 60 | 61 | # Highlight code that enqueued background job in logs. 62 | config.active_job.verbose_enqueue_logs = true 63 | 64 | # Suppress logger output for asset requests. 65 | config.assets.quiet = true 66 | 67 | # Raises error for missing translations. 68 | # config.i18n.raise_on_missing_translations = true 69 | 70 | # Annotate rendered view with file names. 71 | # config.action_view.annotate_rendered_view_with_filenames = true 72 | 73 | # Uncomment if you wish to allow Action Cable access from any origin. 74 | config.action_cable.disable_request_forgery_protection = true 75 | 76 | # Raise error when a before_action's only/except options reference missing actions 77 | config.action_controller.raise_on_missing_callback_actions = true 78 | 79 | # Serve all domains. 80 | config.hosts = nil 81 | end 82 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'active_support/core_ext/integer/time' 4 | 5 | Rails.application.configure do 6 | # Settings specified here will take precedence over those in config/application.rb. 7 | 8 | # Code is not reloaded between requests. 9 | config.enable_reloading = false 10 | 11 | # Eager load code on boot. This eager loads most of Rails and 12 | # your application in memory, allowing both threaded web servers 13 | # and those relying on copy on write to perform better. 14 | # Rake tasks automatically ignore this option for performance. 15 | config.eager_load = true 16 | 17 | # Full error reports are disabled and caching is turned on. 18 | config.consider_all_requests_local = false 19 | config.action_controller.perform_caching = true 20 | 21 | # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment 22 | # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). 23 | # config.require_master_key = true 24 | 25 | # Enable static file serving from the `/public` folder (turn off if using NGINX/Apache for it). 26 | config.public_file_server.enabled = true 27 | 28 | # Compress CSS using a preprocessor. 29 | # config.assets.css_compressor = :sass 30 | 31 | # Do not fallback to assets pipeline if a precompiled asset is missed. 32 | config.assets.compile = false 33 | 34 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 35 | # config.asset_host = "http://assets.example.com" 36 | 37 | # Specifies the header that your server uses for sending files. 38 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache 39 | # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX 40 | 41 | # Store uploaded files on the local file system (see config/storage.yml for options). 42 | config.active_storage.service = :local 43 | 44 | # Mount Action Cable outside main process or domain. 45 | # config.action_cable.mount_path = nil 46 | # config.action_cable.url = "wss://example.com/cable" 47 | # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] 48 | 49 | # Assume all access to the app is happening through a SSL-terminating reverse proxy. 50 | # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. 51 | # config.assume_ssl = true 52 | 53 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 54 | config.force_ssl = true 55 | 56 | # Log to STDOUT by default 57 | config.logger = ActiveSupport::Logger.new($stdout) 58 | .tap { |logger| logger.formatter = Logger::Formatter.new } 59 | .then { |logger| ActiveSupport::TaggedLogging.new(logger) } 60 | 61 | # Prepend all log lines with the following tags. 62 | config.log_tags = [:request_id] 63 | 64 | # Info include generic and useful information about system operation, but avoids logging too much 65 | # information to avoid inadvertent exposure of personally identifiable information (PII). If you 66 | # want to log everything, set the level to "debug". 67 | config.log_level = ENV.fetch('RAILS_LOG_LEVEL', 'info') 68 | 69 | # Use a different cache store in production. 70 | # config.cache_store = :mem_cache_store 71 | 72 | # Use a real queuing backend for Active Job (and separate queues per environment). 73 | # config.active_job.queue_adapter = :resque 74 | # config.active_job.queue_name_prefix = "approximated_example_production" 75 | 76 | config.action_mailer.perform_caching = false 77 | 78 | # Ignore bad email addresses and do not raise email delivery errors. 79 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 80 | # config.action_mailer.raise_delivery_errors = false 81 | 82 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 83 | # the I18n.default_locale when a translation cannot be found). 84 | config.i18n.fallbacks = true 85 | 86 | # Don't log any deprecations. 87 | config.active_support.report_deprecations = false 88 | 89 | # Do not dump schema after migrations. 90 | config.active_record.dump_schema_after_migration = false 91 | 92 | # Enable DNS rebinding protection and other `Host` header attacks. 93 | # config.hosts = [ 94 | # "example.com", # Allow requests from example.com 95 | # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` 96 | # ] 97 | # Skip DNS rebinding protection for the default health check endpoint. 98 | # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } 99 | end 100 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'active_support/core_ext/integer/time' 4 | 5 | # The test environment is used exclusively to run your application's 6 | # test suite. You never need to work with it otherwise. Remember that 7 | # your test database is "scratch space" for the test suite and is wiped 8 | # and recreated between test runs. Don't rely on the data there! 9 | 10 | Rails.application.configure do 11 | # Settings specified here will take precedence over those in config/application.rb. 12 | 13 | # While tests run files are not watched, reloading is not necessary. 14 | config.enable_reloading = false 15 | 16 | # Eager loading loads your entire application. When running a single test locally, 17 | # this is usually not necessary, and can slow down your test suite. However, it's 18 | # recommended that you enable it in continuous integration systems to ensure eager 19 | # loading is working properly before deploying your code. 20 | config.eager_load = ENV['CI'].present? 21 | 22 | # Configure public file server for tests with Cache-Control for performance. 23 | config.public_file_server.enabled = true 24 | config.public_file_server.headers = { 25 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 26 | } 27 | 28 | # Show full error reports and disable caching. 29 | config.consider_all_requests_local = true 30 | config.action_controller.perform_caching = false 31 | config.cache_store = :null_store 32 | 33 | # Raise exceptions instead of rendering exception templates. 34 | config.action_dispatch.show_exceptions = :rescuable 35 | 36 | # Disable request forgery protection in test environment. 37 | config.action_controller.allow_forgery_protection = false 38 | 39 | # Store uploaded files on the local file system in a temporary directory. 40 | config.active_storage.service = :test 41 | 42 | config.action_mailer.perform_caching = false 43 | 44 | # Tell Action Mailer not to deliver emails to the real world. 45 | # The :test delivery method accumulates sent emails in the 46 | # ActionMailer::Base.deliveries array. 47 | config.action_mailer.delivery_method = :test 48 | 49 | # Print deprecation notices to the stderr. 50 | config.active_support.deprecation = :stderr 51 | 52 | # Raise exceptions for disallowed deprecations. 53 | config.active_support.disallowed_deprecation = :raise 54 | 55 | # Tell Active Support which deprecation messages to disallow. 56 | config.active_support.disallowed_deprecation_warnings = [] 57 | 58 | # Raises error for missing translations. 59 | # config.i18n.raise_on_missing_translations = true 60 | 61 | # Annotate rendered view with file names. 62 | # config.action_view.annotate_rendered_view_with_filenames = true 63 | 64 | # Raise error when a before_action's only/except options reference missing actions 65 | config.action_controller.raise_on_missing_callback_actions = true 66 | end 67 | -------------------------------------------------------------------------------- /config/importmap.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Pin npm packages by running ./bin/importmap 4 | 5 | pin 'application', preload: true 6 | pin '@hotwired/turbo-rails', to: 'turbo.min.js', preload: true 7 | pin '@hotwired/stimulus', to: 'stimulus.min.js', preload: true 8 | pin '@hotwired/stimulus-loading', to: 'stimulus-loading.js', preload: true 9 | pin_all_from 'app/javascript/controllers', under: 'controllers' 10 | pin 'autosize', to: 'https://ga.jspm.io/npm:autosize@6.0.1/dist/autosize.esm.js' 11 | -------------------------------------------------------------------------------- /config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Version of your assets, change this if you want to expire all your assets. 6 | Rails.application.config.assets.version = '1.0' 7 | 8 | # Add additional assets to the asset load path. 9 | # Rails.application.config.assets.paths << Emoji.images_path 10 | 11 | # Precompile additional assets. 12 | # application.js, application.css, and all non-JS/CSS in the app/assets 13 | # folder are already added. 14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 15 | -------------------------------------------------------------------------------- /config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Define an application-wide content security policy. 6 | # See the Securing Rails Applications Guide for more information: 7 | # https://guides.rubyonrails.org/security.html#content-security-policy-header 8 | 9 | # Rails.application.configure do 10 | # config.content_security_policy do |policy| 11 | # policy.default_src :self, :https 12 | # policy.font_src :self, :https, :data 13 | # policy.img_src :self, :https, :data 14 | # policy.object_src :none 15 | # policy.script_src :self, :https 16 | # policy.style_src :self, :https 17 | # # Specify URI for violation reports 18 | # # policy.report_uri "/csp-violation-report-endpoint" 19 | # end 20 | # 21 | # # Generate session nonces for permitted importmap, inline scripts, and inline styles. 22 | # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } 23 | # config.content_security_policy_nonce_directives = %w(script-src style-src) 24 | # 25 | # # Report violations without enforcing the policy. 26 | # # config.content_security_policy_report_only = true 27 | # end 28 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. 6 | # Use this to limit dissemination of sensitive information. 7 | # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. 8 | Rails.application.config.filter_parameters += %i[ 9 | passw secret token _key crypt salt certificate otp ssn 10 | ] 11 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Add new inflection rules using the following format. Inflections 6 | # are locale specific, and you may define rules for as many different 7 | # locales as you wish. All of these examples are active by default: 8 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 9 | # inflect.plural /^(ox)$/i, "\\1en" 10 | # inflect.singular /^(ox)en/i, "\\1" 11 | # inflect.irregular "person", "people" 12 | # inflect.uncountable %w( fish sheep ) 13 | # end 14 | 15 | # These inflection rules are supported but not enabled by default: 16 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 17 | # inflect.acronym "RESTful" 18 | # end 19 | -------------------------------------------------------------------------------- /config/initializers/permissions_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Define an application-wide HTTP permissions policy. For further 6 | # information see: https://developers.google.com/web/updates/2018/06/feature-policy 7 | 8 | # Rails.application.config.permissions_policy do |policy| 9 | # policy.camera :none 10 | # policy.gyroscope :none 11 | # policy.microphone :none 12 | # policy.usb :none 13 | # policy.fullscreen :self 14 | # policy.payment :self, "https://secure.example.com" 15 | # end 16 | -------------------------------------------------------------------------------- /config/initializers/public_suffix.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | if Rails.env.development? 4 | # Allow test domain in development env 5 | PublicSuffix::List.default << PublicSuffix::Rule.factory('test') 6 | end 7 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization and 2 | # are automatically loaded by Rails. If you want to use locales other than 3 | # 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 about the API, please read the Rails Internationalization guide 20 | # at https://guides.rubyonrails.org/i18n.html. 21 | # 22 | # Be aware that YAML interprets the following case-insensitive strings as 23 | # booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings 24 | # must be quoted to be interpreted as strings. For example: 25 | # 26 | # en: 27 | # "yes": yup 28 | # enabled: "ON" 29 | 30 | en: 31 | hello: "Hello world" 32 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This configuration file will be evaluated by Puma. The top-level methods that 4 | # are invoked here are part of Puma's configuration DSL. For more information 5 | # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. 6 | 7 | # Puma can serve each request in a thread from an internal thread pool. 8 | # The `threads` method setting takes two numbers: a minimum and maximum. 9 | # Any libraries that use thread pools should be configured to match 10 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 11 | # and maximum; this matches the default thread size of Active Record. 12 | max_threads_count = ENV.fetch('RAILS_MAX_THREADS', 5) 13 | min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } 14 | threads min_threads_count, max_threads_count 15 | 16 | # Specifies that the worker count should equal the number of processors in production. 17 | if ENV['RAILS_ENV'] == 'production' 18 | require 'concurrent-ruby' 19 | worker_count = Integer(ENV.fetch('WEB_CONCURRENCY') { Concurrent.physical_processor_count }) 20 | workers worker_count if worker_count > 1 21 | end 22 | 23 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 24 | # terminating a worker in development environments. 25 | worker_timeout 3600 if ENV.fetch('RAILS_ENV', 'development') == 'development' 26 | 27 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 28 | port ENV.fetch('PORT', 3000) 29 | 30 | # Specifies the `environment` that Puma will run in. 31 | environment ENV.fetch('RAILS_ENV', 'development') 32 | 33 | # Specifies the `pidfile` that Puma will use. 34 | pidfile ENV.fetch('PIDFILE', 'tmp/pids/server.pid') 35 | 36 | # Allow puma to be restarted by `bin/rails restart` command. 37 | plugin :tmp_restart 38 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | constraints AppDomainConstraint do 5 | root 'pages#index', as: :pages_root 6 | resources :pages, except: %i[index] 7 | end 8 | 9 | constraints !AppDomainConstraint do 10 | root 'public_pages#show', as: :public_pages_root 11 | end 12 | 13 | get 'up' => 'rails/health#show', as: :rails_health_check 14 | end 15 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket-<%= Rails.env %> 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket-<%= Rails.env %> 23 | 24 | # Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name-<%= Rails.env %> 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /config/tailwind.config.js: -------------------------------------------------------------------------------- 1 | const defaultTheme = require('tailwindcss/defaultTheme') 2 | 3 | module.exports = { 4 | content: [ 5 | './app/helpers/**/*.rb', 6 | './app/javascript/**/*.js', 7 | './app/views/**/*.html.erb' 8 | ], 9 | 10 | theme: { 11 | extend: { 12 | fontFamily: { 13 | sans: ['Inter var', ...defaultTheme.fontFamily.sans], 14 | }, 15 | }, 16 | }, 17 | 18 | plugins: [ 19 | require('@tailwindcss/forms'), 20 | require('@tailwindcss/typography'), 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /db/migrate/20230721090602_create_pages.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class CreatePages < ActiveRecord::Migration[7.0] 4 | def change 5 | create_table :pages do |t| 6 | t.string :title, null: false 7 | t.text :content, null: false 8 | t.string :domain, null: false 9 | 10 | t.timestamps 11 | 12 | t.index :domain, unique: true 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /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 | # This file is the source Rails uses to define your schema when running `bin/rails 6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema[7.1].define(version: 2023_07_21_090602) do 14 | create_table "pages", force: :cascade do |t| 15 | t.string "title", null: false 16 | t.text "content", null: false 17 | t.string "domain", null: false 18 | t.datetime "created_at", null: false 19 | t.datetime "updated_at", null: false 20 | t.index ["domain"], name: "index_pages_on_domain", unique: true 21 | end 22 | 23 | end 24 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file should ensure the existence of records required to run the application in every environment (production, 4 | # development, test). The code here should be idempotent so that it can be executed at any point in every environment. 5 | # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). 6 | # 7 | # Example: 8 | # 9 | # ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| 10 | # MovieGenre.find_or_create_by!(name: genre_name) 11 | # end 12 | -------------------------------------------------------------------------------- /lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/lib/assets/.keep -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/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/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/storage/.keep -------------------------------------------------------------------------------- /test/application_system_test_case.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | require 'capybara/cuprite' 5 | 6 | class ApplicationSystemTestCase < ActionDispatch::SystemTestCase 7 | driven_by :cuprite, screen_size: [1400, 1400], options: { js_errors: true } 8 | end 9 | -------------------------------------------------------------------------------- /test/channels/application_cable/connection_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | module ApplicationCable 6 | class ConnectionTest < ActionCable::Connection::TestCase 7 | # test "connects with cookies" do 8 | # cookies.signed[:user_id] = 42 9 | # 10 | # connect 11 | # 12 | # assert_equal connection.user_id, "42" 13 | # end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/controllers/.keep -------------------------------------------------------------------------------- /test/controllers/pages_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class PagesControllerTest < ActionDispatch::IntegrationTest 6 | setup do 7 | host! ENV.fetch('APP_PRIMARY_DOMAIN') 8 | end 9 | 10 | def test_app_domain_routing 11 | get URI::HTTP.build(host: ENV.fetch('APP_PRIMARY_DOMAIN'), path: '/').to_s 12 | 13 | assert_equal 'pages', @controller.controller_name 14 | assert_equal 'index', @controller.action_name 15 | assert_response :success 16 | end 17 | 18 | def test_index 19 | get pages_root_url 20 | 21 | assert_response :success 22 | end 23 | 24 | def test_new 25 | get new_page_url 26 | 27 | assert_response :success 28 | end 29 | 30 | def test_create 31 | stub_apx_create_request( 32 | :success, body: { 33 | incoming_address: 'new-page.com', 34 | target_address: ENV.fetch('APP_PRIMARY_DOMAIN') 35 | } 36 | ) 37 | 38 | new_attrs = { title: 'New Page', content: 'New page content', domain: 'new-page.com' } 39 | 40 | assert_difference('Page.count') do 41 | post pages_url, params: { page: new_attrs } 42 | end 43 | 44 | page = Page.order(:created_at).last 45 | 46 | assert_equal new_attrs[:title], page.title 47 | assert_equal new_attrs[:content], page.content 48 | assert_equal new_attrs[:domain], page.domain 49 | 50 | assert_redirected_to page_url(page) 51 | end 52 | 53 | def test_show 54 | get page_url(pages(:one)) 55 | 56 | assert_response :success 57 | end 58 | 59 | def test_edit 60 | get edit_page_url(pages(:one)) 61 | 62 | assert_response :success 63 | end 64 | 65 | def test_update 66 | page = pages(:one) 67 | 68 | stub_apx_read_request(:success, incoming_address: page.domain) 69 | 70 | stub_apx_update_request( 71 | :success, body: { 72 | current_incoming_address: page.domain, 73 | incoming_address: 'updated-domain.com' 74 | } 75 | ) 76 | 77 | new_attrs = { title: 'Updated page', content: 'Updated content', domain: 'updated-domain.com' } 78 | patch page_url(page), params: { page: new_attrs } 79 | 80 | page.reload 81 | 82 | assert_equal new_attrs[:title], page.title 83 | assert_equal new_attrs[:content], page.content 84 | assert_equal new_attrs[:domain], page.domain 85 | 86 | assert_redirected_to page_url(page) 87 | end 88 | 89 | def test_destroy 90 | page = pages(:one) 91 | 92 | stub_apx_delete_request(:success, incoming_address: page.domain) 93 | 94 | assert_difference('Page.count', -1) do 95 | delete page_url(page) 96 | end 97 | 98 | assert_redirected_to pages_root_url 99 | end 100 | end 101 | -------------------------------------------------------------------------------- /test/controllers/public_pages_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class PublicPagesControllerTest < ActionDispatch::IntegrationTest 6 | setup do 7 | @page = pages(:one) 8 | host! @page.domain 9 | end 10 | 11 | def test_page_domain_routing_via_host 12 | get URI::HTTP.build(host: @page.domain, path: '/').to_s 13 | 14 | assert_equal 'public_pages', @controller.controller_name 15 | assert_equal 'show', @controller.action_name 16 | assert_response :success 17 | end 18 | 19 | def test_page_domain_routing_via_header 20 | url = URI::HTTP.build(host: ENV.fetch('APP_PRIMARY_DOMAIN'), path: '/').to_s 21 | get url, headers: { 'apx-incoming-host' => @page.domain } 22 | 23 | assert_equal 'public_pages', @controller.controller_name 24 | assert_equal 'show', @controller.action_name 25 | assert_response :success 26 | end 27 | 28 | def test_show 29 | get public_pages_root_path 30 | 31 | assert_response :success 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/fixtures/files/approximated/create.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "id": 445922, 4 | "incoming_address": "incoming.com", 5 | "target_address": "target.com", 6 | "target_ports": "443", 7 | "user_message": "In order to connect your domain, you'll need to have a DNS A record that points acustomdomain.com at 213.188.210.168. If you already have an A record for that address, please change it to point at 213.188.210.168 and remove any other A records for that exact address. It may take a few minutes for your SSL certificate to take effect once you've pointed your DNS A record." 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/fixtures/files/approximated/read.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "apx_hit": true, 4 | "created_at": "2023-04-03T17:59:28", 5 | "dns_pointed_at": "213.188.210.168", 6 | "has_ssl": true, 7 | "id": 405455, 8 | "incoming_address": "incoming.com", 9 | "is_resolving": true, 10 | "last_monitored_humanized": "1 hour ago", 11 | "last_monitored_unix": 1687194590, 12 | "ssl_active_from": "2023-06-02T20:19:15", 13 | "ssl_active_until": "2023-08-31T20:19:14", 14 | "status": "ACTIVE_SSL", 15 | "status_message": "Active with SSL", 16 | "target_address": "target.com", 17 | "target_ports": "443" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/fixtures/files/approximated/update.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "apx_hit": true, 4 | "created_at": "2023-04-03T17:59:28", 5 | "dns_pointed_at": "213.188.210.168", 6 | "has_ssl": true, 7 | "id": 405455, 8 | "incoming_address": "incoming.com", 9 | "is_resolving": true, 10 | "last_monitored_humanized": "1 hour ago", 11 | "last_monitored_unix": 1687194590, 12 | "ssl_active_from": "2023-06-02T20:19:15", 13 | "ssl_active_until": "2023-08-31T20:19:14", 14 | "status": "ACTIVE_SSL", 15 | "status_message": "Active with SSL", 16 | "target_address": "target.com", 17 | "target_ports": "443" 18 | } 19 | } -------------------------------------------------------------------------------- /test/fixtures/pages.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | one: 4 | title: Page One 5 | content: Page One Content 6 | domain: page-one.com 7 | -------------------------------------------------------------------------------- /test/helpers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/helpers/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/models/.keep -------------------------------------------------------------------------------- /test/models/page_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class PageTest < ActiveSupport::TestCase 6 | def setup 7 | @page = Page.new(title: 'Page', content: 'Content', domain: 'custom-domain.com') 8 | end 9 | 10 | def test_valid 11 | assert_predicate @page, :valid? 12 | end 13 | 14 | def test_invalid_without_title 15 | @page.title = nil 16 | 17 | assert_invalid_attr @page, :title 18 | end 19 | 20 | def test_invalid_without_content 21 | @page.content = nil 22 | 23 | assert_invalid_attr @page, :content 24 | end 25 | 26 | def test_invalid_without_domain 27 | @page.domain = nil 28 | 29 | assert_invalid_attr @page, :domain 30 | end 31 | 32 | def test_valid_with_subdomain 33 | @page.domain = 'custom.domain.com' 34 | 35 | assert_predicate @page, :valid? 36 | end 37 | 38 | def test_invalid_with_custom_tld 39 | @page.domain = 'domain.tldnotlisted' 40 | 41 | assert_invalid_attr @page, :domain 42 | end 43 | 44 | def test_invalid_without_sld 45 | @page.domain = 'com' 46 | 47 | assert_invalid_attr @page, :domain 48 | end 49 | 50 | def test_invalid_with_restricted_domain 51 | @page.domain = ENV.fetch('APP_PRIMARY_DOMAIN') 52 | 53 | assert_invalid_attr @page, :domain 54 | end 55 | 56 | def test_invalid_without_unique_domain 57 | @page.domain = pages(:one).domain 58 | 59 | assert_invalid_attr @page, :domain 60 | end 61 | 62 | def test_create_apx_vhost 63 | body = { 64 | incoming_address: @page.domain, 65 | target_address: ENV.fetch('APP_PRIMARY_DOMAIN') 66 | } 67 | 68 | stub_apx_create_request(:unauthorized, body:) 69 | 70 | assert_not @page.save 71 | 72 | stub_apx_create_request(:success, body:) 73 | 74 | assert @page.save 75 | end 76 | 77 | def test_update_existing_apx_vhost 78 | page = pages(:one) 79 | 80 | stub_apx_read_request(:success, incoming_address: page.domain) 81 | 82 | body = { 83 | current_incoming_address: page.domain, 84 | incoming_address: 'updated-domain.com' 85 | } 86 | 87 | stub_apx_update_request(:unauthorized, body:) 88 | 89 | assert_not page.update(domain: 'updated-domain.com') 90 | 91 | stub_apx_update_request(:success, body:) 92 | 93 | assert page.update(domain: 'updated-domain.com') 94 | end 95 | 96 | def test_update_missing_apx_vhost 97 | page = pages(:one) 98 | 99 | stub_apx_read_request(:unauthorized, incoming_address: page.domain) 100 | 101 | assert_not page.update(domain: 'updated-domain.com') 102 | 103 | stub_apx_read_request(:not_found, incoming_address: page.domain) 104 | 105 | stub_apx_create_request( 106 | :success, body: { 107 | incoming_address: 'updated-domain.com', 108 | target_address: ENV.fetch('APP_PRIMARY_DOMAIN') 109 | } 110 | ) 111 | 112 | assert page.update(domain: 'updated-domain.com') 113 | end 114 | 115 | def test_delete_apx_vhost 116 | page = pages(:one) 117 | 118 | stub_apx_delete_request(:unauthorized, incoming_address: page.domain) 119 | 120 | assert_not page.destroy 121 | 122 | stub_apx_delete_request(:success, incoming_address: page.domain) 123 | 124 | assert page.destroy 125 | end 126 | 127 | private 128 | 129 | def assert_invalid_attr(page, attr_name) 130 | assert_not_predicate page, :valid? 131 | assert_predicate page.errors[attr_name], :present? 132 | end 133 | end 134 | -------------------------------------------------------------------------------- /test/services/approximated/creating_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Approximated 6 | class CreatingTest < ActiveSupport::TestCase 7 | def setup 8 | @apx = Approximated.new 9 | 10 | @request_data = { 11 | incoming_address: 'incoming.com', 12 | target_address: 'target.com', 13 | exact_match: false 14 | } 15 | end 16 | 17 | def test_success 18 | api_response = stub_apx_create_request(:success, body: @request_data) 19 | apx_result = create_apx_vhost 20 | 21 | assert_equal 201, apx_result.status 22 | assert_equal api_response, apx_result.body 23 | end 24 | 25 | def test_unauthorized 26 | stub_apx_create_request(:unauthorized, body: @request_data) 27 | assert_raises(Approximated::UnauthorizedError) { create_apx_vhost } 28 | end 29 | 30 | private 31 | 32 | def create_apx_vhost 33 | @apx.create_vhost( 34 | @request_data[:incoming_address], 35 | @request_data[:target_address], 36 | exact_match: @request_data[:exact_match] 37 | ) 38 | end 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /test/services/approximated/deleting_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Approximated 6 | class DeletingTest < ActiveSupport::TestCase 7 | def setup 8 | @apx = Approximated.new 9 | @incoming_address = 'incoming.com' 10 | end 11 | 12 | def test_success 13 | stub_apx_delete_request(:success, incoming_address: @incoming_address) 14 | apx_result = delete_apx_vhost 15 | 16 | assert_equal 200, apx_result.status 17 | assert_nil apx_result.body 18 | end 19 | 20 | def test_unauthorized 21 | stub_apx_delete_request(:unauthorized, incoming_address: @incoming_address) 22 | assert_raises(Approximated::UnauthorizedError) { delete_apx_vhost } 23 | end 24 | 25 | def test_not_found 26 | stub_apx_delete_request(:not_found, incoming_address: @incoming_address) 27 | assert_raises(Approximated::ResourceNotFound) { delete_apx_vhost } 28 | end 29 | 30 | private 31 | 32 | def delete_apx_vhost 33 | @apx.delete_vhost(@incoming_address) 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /test/services/approximated/reading_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Approximated 6 | class ReadingTest < ActiveSupport::TestCase 7 | def setup 8 | @apx = Approximated.new 9 | @incoming_address = 'incoming.com' 10 | end 11 | 12 | def test_success 13 | api_response = stub_apx_read_request(:success, incoming_address: @incoming_address) 14 | apx_result = read_apx_vhost 15 | 16 | assert_equal 200, apx_result.status 17 | assert_equal api_response, apx_result.body 18 | end 19 | 20 | def test_unauthorized 21 | stub_apx_read_request(:unauthorized, incoming_address: @incoming_address) 22 | assert_raises(Approximated::UnauthorizedError) { read_apx_vhost } 23 | end 24 | 25 | def test_not_found 26 | stub_apx_read_request(:not_found, incoming_address: @incoming_address) 27 | assert_raises(Approximated::ResourceNotFound) { read_apx_vhost } 28 | end 29 | 30 | private 31 | 32 | def read_apx_vhost 33 | @apx.get_vhost(@incoming_address) 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /test/services/approximated/updating_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Approximated 6 | class UpdatingTest < ActiveSupport::TestCase 7 | def setup 8 | @apx = Approximated.new 9 | 10 | @request_data = { 11 | current_incoming_address: 'incoming.com', 12 | incoming_address: 'new-incoming.com', 13 | exact_match: true 14 | } 15 | end 16 | 17 | def test_success 18 | api_response = stub_apx_update_request(:success, body: @request_data) 19 | apx_result = update_apx_vhost 20 | 21 | assert_equal 200, apx_result.status 22 | assert_equal api_response, apx_result.body 23 | end 24 | 25 | def test_unauthorized 26 | stub_apx_update_request(:unauthorized, body: @request_data) 27 | assert_raises(Approximated::UnauthorizedError) { update_apx_vhost } 28 | end 29 | 30 | def test_not_found 31 | stub_apx_update_request(:not_found, body: @request_data) 32 | assert_raises(Approximated::ResourceNotFound) { update_apx_vhost } 33 | end 34 | 35 | private 36 | 37 | def update_apx_vhost 38 | @apx.update_vhost( 39 | @request_data[:current_incoming_address], 40 | incoming_address: @request_data[:incoming_address], 41 | exact_match: @request_data[:exact_match] 42 | ) 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /test/support/approximated_helpers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TestSupport 4 | module ApproximatedHelpers 5 | def stub_apx_create_request(scenario, body:) 6 | case scenario 7 | when :success 8 | stub_apx_request('/api/vhosts', :post, body, 201, 'create.json') 9 | when :unauthorized 10 | stub_apx_request('/api/vhosts', :post, body, 401, nil) 11 | else 12 | raise ArgumentError, 'Unknown scenario' 13 | end 14 | end 15 | 16 | def stub_apx_update_request(scenario, body:) 17 | case scenario 18 | when :success 19 | stub_apx_request('/api/vhosts/update/by/incoming', :post, body, 200, 'update.json') 20 | when :unauthorized 21 | stub_apx_request('/api/vhosts/update/by/incoming', :post, body, 401, nil) 22 | when :not_found 23 | stub_apx_request('/api/vhosts/update/by/incoming', :post, body, 404, nil) 24 | else 25 | raise ArgumentError, 'Unknown scenario' 26 | end 27 | end 28 | 29 | def stub_apx_read_request(scenario, incoming_address:) 30 | case scenario 31 | when :success 32 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :get, '', 200, 'read.json') 33 | when :unauthorized 34 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :get, '', 401, nil) 35 | when :not_found 36 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :get, '', 404, nil) 37 | else 38 | raise ArgumentError, 'Unknown scenario' 39 | end 40 | end 41 | 42 | def stub_apx_delete_request(scenario, incoming_address:) 43 | case scenario 44 | when :success 45 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :delete, '', 200, nil) 46 | when :unauthorized 47 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :delete, '', 401, nil) 48 | when :not_found 49 | stub_apx_request("/api/vhosts/by/incoming/#{incoming_address}", :delete, '', 404, nil) 50 | else 51 | raise ArgumentError, 'Unknown scenario' 52 | end 53 | end 54 | 55 | private 56 | 57 | def stub_apx_request(path, method, request_body, status, response_file) 58 | request_url = URI::HTTPS.build(host: 'cloud.approximated.app', path:).to_s 59 | response_body = response_file ? file_fixture(File.join('approximated', response_file)).read : nil 60 | 61 | stub_request(method, request_url).with( 62 | body: request_body, 63 | headers: { 'api-key' => ENV.fetch('APPROXIMATED_API_KEY') } 64 | ).to_return( 65 | status:, 66 | body: response_body, 67 | headers: { 'Content-Type' => 'application/json' } 68 | ) 69 | 70 | response_body.present? ? JSON.parse(response_body) : response_body 71 | end 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /test/system/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/test/system/.keep -------------------------------------------------------------------------------- /test/system/pages_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'application_system_test_case' 4 | 5 | class PagesTest < ApplicationSystemTestCase 6 | setup do 7 | page.driver.add_headers('apx-incoming-host' => ENV.fetch('APP_PRIMARY_DOMAIN')) 8 | end 9 | 10 | def test_index 11 | visit pages_root_url 12 | 13 | assert_selector 'h1', text: 'Pages' 14 | end 15 | 16 | def test_show 17 | visit pages_root_url 18 | click_link pages(:one).title 19 | 20 | assert_selector 'h1', text: pages(:one).title 21 | end 22 | 23 | def test_create 24 | stub_apx_create_request( 25 | :success, body: { 26 | incoming_address: 'my-new-page.com', 27 | target_address: ENV.fetch('APP_PRIMARY_DOMAIN') 28 | } 29 | ) 30 | 31 | visit pages_root_url 32 | click_link 'New page' 33 | 34 | fill_in 'Title', with: 'My New Page' 35 | fill_in 'Content', with: 'My new page content' 36 | fill_in 'Domain', with: 'my-new-page.com' 37 | 38 | click_button 'Create page' 39 | 40 | assert_text <<~MESSAGE.squish 41 | In order to connect your domain, you'll need to have a DNS A record that points acustomdomain.com 42 | at 213.188.210.168. If you already have an A record for that address, please change it to point 43 | at 213.188.210.168 and remove any other A records for that exact address. It may take a few minutes 44 | for your SSL certificate to take effect once you've pointed your DNS A record. 45 | MESSAGE 46 | 47 | assert_selector 'h1', text: 'My New Page' 48 | end 49 | 50 | def test_update 51 | stub_apx_read_request(:success, incoming_address: pages(:one).domain) 52 | 53 | stub_apx_update_request( 54 | :success, body: { 55 | current_incoming_address: pages(:one).domain, 56 | incoming_address: 'my-updated-page.com' 57 | } 58 | ) 59 | 60 | visit page_url(pages(:one)) 61 | click_link 'Edit this page' 62 | 63 | fill_in 'Title', with: 'My Updated Page' 64 | fill_in 'Content', with: 'My updated page content' 65 | fill_in 'Domain', with: 'my-updated-page.com' 66 | 67 | click_button 'Save page' 68 | 69 | assert_text 'Page was successfully updated.' 70 | assert_selector 'h1', text: 'My Updated Page' 71 | end 72 | 73 | def test_destroy 74 | stub_apx_delete_request(:success, incoming_address: pages(:one).domain) 75 | 76 | visit page_url(pages(:one)) 77 | 78 | accept_confirm do 79 | click_link 'Destroy this page' 80 | end 81 | 82 | assert_text 'Page was successfully destroyed.' 83 | assert_selector 'h1', text: 'Pages' 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /test/system/public_pages_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'application_system_test_case' 4 | 5 | class PublicPagesTest < ApplicationSystemTestCase 6 | setup do 7 | @page = pages(:one) 8 | page.driver.add_headers('apx-incoming-host' => @page.domain) 9 | end 10 | 11 | def test_show 12 | visit public_pages_root_url 13 | 14 | assert_selector 'h1', text: @page.title 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require_relative '../config/environment' 5 | require 'rails/test_help' 6 | 7 | require 'webmock/minitest' 8 | 9 | require 'support/approximated_helpers' 10 | 11 | module ActiveSupport 12 | class TestCase 13 | include TestSupport::ApproximatedHelpers 14 | 15 | # Run tests in parallel with specified workers 16 | parallelize(workers: :number_of_processors) 17 | 18 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 19 | fixtures :all 20 | 21 | # Disable external requests by default 22 | WebMock.disable_net_connect!(allow_localhost: true) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/tmp/.keep -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/tmp/pids/.keep -------------------------------------------------------------------------------- /tmp/storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/tmp/storage/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Approximated-Inc/rails-custom-domains-example/8dc647ad934c4102905c9e3a11476bc1b38134c8/vendor/.keep --------------------------------------------------------------------------------