From 99464ea25920d0d8e9623b2c3df11c2615aebf89 Mon Sep 17 00:00:00 2001 From: kseastman Date: Mon, 7 May 2018 12:51:23 -0700 Subject: [PATCH 01/36] initialize new rails app --- .gitignore | 16 ++ Gemfile | 50 ++++++ Gemfile.lock | 154 ++++++++++++++++++ Rakefile | 6 + app/channels/application_cable/channel.rb | 4 + app/channels/application_cable/connection.rb | 4 + app/controllers/application_controller.rb | 2 + app/controllers/concerns/.keep | 0 app/jobs/application_job.rb | 2 + app/mailers/application_mailer.rb | 4 + app/models/application_record.rb | 3 + app/models/concerns/.keep | 0 app/models/customer.rb | 2 + app/models/rental.rb | 2 + app/views/layouts/mailer.html.erb | 13 ++ app/views/layouts/mailer.text.erb | 1 + bin/bundle | 3 + bin/rails | 9 + bin/rake | 9 + bin/setup | 35 ++++ bin/spring | 17 ++ bin/update | 29 ++++ config.ru | 5 + config/application.rb | 40 +++++ config/boot.rb | 3 + config/cable.yml | 10 ++ config/database.yml | 85 ++++++++++ config/environment.rb | 5 + config/environments/development.rb | 47 ++++++ config/environments/production.rb | 83 ++++++++++ config/environments/test.rb | 42 +++++ .../application_controller_renderer.rb | 8 + config/initializers/backtrace_silencers.rb | 7 + config/initializers/cors.rb | 16 ++ .../initializers/filter_parameter_logging.rb | 4 + config/initializers/inflections.rb | 16 ++ config/initializers/mime_types.rb | 4 + config/initializers/wrap_parameters.rb | 14 ++ config/locales/en.yml | 33 ++++ config/puma.rb | 56 +++++++ config/routes.rb | 3 + config/secrets.yml | 32 ++++ config/spring.rb | 6 + db/migrate/20180507194317_create_movies.rb | 12 ++ db/migrate/20180507194620_create_customers.rb | 14 ++ db/migrate/20180507194739_create_rentals.rb | 13 ++ db/schema.rb | 50 ++++++ lib/tasks/.keep | 0 log/.keep | 0 public/robots.txt | 1 + test/controllers/.keep | 0 test/fixtures/.keep | 0 test/fixtures/customers.yml | 17 ++ test/fixtures/files/.keep | 0 test/fixtures/rentals.yml | 11 ++ test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/models/customer_test.rb | 9 + test/models/rental_test.rb | 9 + test/test_helper.rb | 26 +++ tmp/.keep | 0 vendor/.keep | 0 63 files changed, 1046 insertions(+) create mode 100644 .gitignore create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 Rakefile create mode 100644 app/channels/application_cable/channel.rb create mode 100644 app/channels/application_cable/connection.rb create mode 100644 app/controllers/application_controller.rb create mode 100644 app/controllers/concerns/.keep create mode 100644 app/jobs/application_job.rb create mode 100644 app/mailers/application_mailer.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/concerns/.keep create mode 100644 app/models/customer.rb create mode 100644 app/models/rental.rb create mode 100644 app/views/layouts/mailer.html.erb create mode 100644 app/views/layouts/mailer.text.erb create mode 100755 bin/bundle create mode 100755 bin/rails create mode 100755 bin/rake create mode 100755 bin/setup create mode 100755 bin/spring create mode 100755 bin/update create mode 100644 config.ru create mode 100644 config/application.rb create mode 100644 config/boot.rb create mode 100644 config/cable.yml create mode 100644 config/database.yml create mode 100644 config/environment.rb create mode 100644 config/environments/development.rb create mode 100644 config/environments/production.rb create mode 100644 config/environments/test.rb create mode 100644 config/initializers/application_controller_renderer.rb create mode 100644 config/initializers/backtrace_silencers.rb create mode 100644 config/initializers/cors.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/initializers/mime_types.rb create mode 100644 config/initializers/wrap_parameters.rb create mode 100644 config/locales/en.yml create mode 100644 config/puma.rb create mode 100644 config/routes.rb create mode 100644 config/secrets.yml create mode 100644 config/spring.rb create mode 100644 db/migrate/20180507194317_create_movies.rb create mode 100644 db/migrate/20180507194620_create_customers.rb create mode 100644 db/migrate/20180507194739_create_rentals.rb create mode 100644 db/schema.rb create mode 100644 lib/tasks/.keep create mode 100644 log/.keep create mode 100644 public/robots.txt create mode 100644 test/controllers/.keep create mode 100644 test/fixtures/.keep create mode 100644 test/fixtures/customers.yml create mode 100644 test/fixtures/files/.keep create mode 100644 test/fixtures/rentals.yml create mode 100644 test/integration/.keep create mode 100644 test/mailers/.keep create mode 100644 test/models/.keep create mode 100644 test/models/customer_test.rb create mode 100644 test/models/rental_test.rb create mode 100644 test/test_helper.rb create mode 100644 tmp/.keep create mode 100644 vendor/.keep diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..68ac019ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +.byebug_history diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..78bff8d26 --- /dev/null +++ b/Gemfile @@ -0,0 +1,50 @@ +source 'https://rubygems.org' + +git_source(:github) do |repo_name| + repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") + "https://github.com/#{repo_name}.git" +end + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '~> 5.1.6' +# Use postgresql as the database for Active Record +gem 'pg', '>= 0.18', '< 2.0' +# Use Puma as the app server +gem 'puma', '~> 3.7' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +# gem 'jbuilder', '~> 2.5' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 4.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] +end + +group :development do + gem 'listen', '>= 3.0.5', '< 3.2' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] + +group :development, :test do + gem 'pry-rails' +end + +group :test do + gem 'minitest-rails' + gem 'minitest-reporters' +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..e547d2449 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,154 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.1.6) + actionpack (= 5.1.6) + nio4r (~> 2.0) + websocket-driver (~> 0.6.1) + actionmailer (5.1.6) + actionpack (= 5.1.6) + actionview (= 5.1.6) + activejob (= 5.1.6) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (5.1.6) + actionview (= 5.1.6) + activesupport (= 5.1.6) + rack (~> 2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.1.6) + activesupport (= 5.1.6) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.3) + activejob (5.1.6) + activesupport (= 5.1.6) + globalid (>= 0.3.6) + activemodel (5.1.6) + activesupport (= 5.1.6) + activerecord (5.1.6) + activemodel (= 5.1.6) + activesupport (= 5.1.6) + arel (~> 8.0) + activesupport (5.1.6) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 0.7, < 2) + minitest (~> 5.1) + tzinfo (~> 1.1) + ansi (1.5.0) + arel (8.0.0) + builder (3.2.3) + byebug (10.0.2) + coderay (1.1.2) + concurrent-ruby (1.0.5) + crass (1.0.4) + erubi (1.7.1) + ffi (1.9.23) + globalid (0.4.1) + activesupport (>= 4.2.0) + i18n (1.0.1) + concurrent-ruby (~> 1.0) + listen (3.1.5) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + ruby_dep (~> 1.2) + loofah (2.2.2) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.7.0) + mini_mime (>= 0.1.1) + method_source (0.9.0) + mini_mime (1.0.0) + mini_portile2 (2.3.0) + minitest (5.11.3) + minitest-rails (3.0.0) + minitest (~> 5.8) + railties (~> 5.0) + minitest-reporters (1.2.0) + ansi + builder + minitest (>= 5.0) + ruby-progressbar + nio4r (2.3.1) + nokogiri (1.8.2) + mini_portile2 (~> 2.3.0) + pg (1.0.0) + pry (0.11.3) + coderay (~> 1.1.0) + method_source (~> 0.9.0) + pry-rails (0.3.6) + pry (>= 0.10.4) + puma (3.11.4) + rack (2.0.5) + rack-test (1.0.0) + rack (>= 1.0, < 3) + rails (5.1.6) + actioncable (= 5.1.6) + actionmailer (= 5.1.6) + actionpack (= 5.1.6) + actionview (= 5.1.6) + activejob (= 5.1.6) + activemodel (= 5.1.6) + activerecord (= 5.1.6) + activesupport (= 5.1.6) + bundler (>= 1.3.0) + railties (= 5.1.6) + sprockets-rails (>= 2.0.0) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.0.4) + loofah (~> 2.2, >= 2.2.2) + railties (5.1.6) + actionpack (= 5.1.6) + activesupport (= 5.1.6) + method_source + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (12.3.1) + rb-fsevent (0.10.3) + rb-inotify (0.9.10) + ffi (>= 0.5.0, < 2) + ruby-progressbar (1.9.0) + ruby_dep (1.5.0) + spring (2.0.2) + activesupport (>= 4.2) + spring-watcher-listen (2.0.1) + listen (>= 2.7, < 4.0) + spring (>= 1.2, < 3.0) + sprockets (3.7.1) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.2.1) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.20.0) + thread_safe (0.3.6) + tzinfo (1.2.5) + thread_safe (~> 0.1) + websocket-driver (0.6.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.3) + +PLATFORMS + ruby + +DEPENDENCIES + byebug + listen (>= 3.0.5, < 3.2) + minitest-rails + minitest-reporters + pg (>= 0.18, < 2.0) + pry-rails + puma (~> 3.7) + rails (~> 5.1.6) + spring + spring-watcher-listen (~> 2.0.0) + tzinfo-data + +BUNDLED WITH + 1.16.1 diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..e85f91391 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..d67269728 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..0ff5442f4 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..4ac8823b0 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..a009ace51 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..286b2239d --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 000000000..10a4cba84 --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/customer.rb b/app/models/customer.rb new file mode 100644 index 000000000..0b5277335 --- /dev/null +++ b/app/models/customer.rb @@ -0,0 +1,2 @@ +class Customer < ApplicationRecord +end diff --git a/app/models/rental.rb b/app/models/rental.rb new file mode 100644 index 000000000..79e3a65ca --- /dev/null +++ b/app/models/rental.rb @@ -0,0 +1,2 @@ +class Rental < ApplicationRecord +end diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..cbd34d2e9 --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 000000000..66e9889e8 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..5badb2fde --- /dev/null +++ b/bin/rails @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/bin/rake b/bin/rake new file mode 100755 index 000000000..d87d5f578 --- /dev/null +++ b/bin/rake @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..104e40c1c --- /dev/null +++ b/bin/setup @@ -0,0 +1,35 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/bin/spring b/bin/spring new file mode 100755 index 000000000..fb2ec2ebb --- /dev/null +++ b/bin/spring @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby + +# This file loads spring without using Bundler, in order to be fast. +# It gets overwritten when you run the `spring binstub` command. + +unless defined?(Spring) + require 'rubygems' + require 'bundler' + + lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) + spring = lockfile.specs.detect { |spec| spec.name == "spring" } + if spring + Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path + gem 'spring', spring.version + require 'spring/binstub' + end +end diff --git a/bin/update b/bin/update new file mode 100755 index 000000000..a8e4462f2 --- /dev/null +++ b/bin/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..f7ba0b527 --- /dev/null +++ b/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..2fe7718ea --- /dev/null +++ b/config/application.rb @@ -0,0 +1,40 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module VideoStoreAPI + class Application < Rails::Application + config.generators do |g| + # Force new test files to be generated in the minitest-spec style + g.test_framework :minitest, spec: true + + # Always use .js files, never .coffee + g.javascript_engine :js + end + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 5.1 + + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..30f5120df --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..ad59bcd88 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: async + +production: + adapter: redis + url: redis://localhost:6379/1 + channel_prefix: VideoStoreAPI_production diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..720570700 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,85 @@ +# PostgreSQL. Versions 9.1 and up are supported. +# +# Install the pg driver: +# gem install pg +# On OS X with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On OS X with MacPorts: +# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem 'pg' +# +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # http://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + +development: + <<: *default + database: VideoStoreAPI_development + + # The specified database role being used to connect to postgres. + # To create additional roles in postgres see `$ createuser --help`. + # When left blank, postgres will use the default role. This is + # the same name as the operating system user that initialized the database. + #username: VideoStoreAPI + + # The password associated with the postgres role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: VideoStoreAPI_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: VideoStoreAPI_production + username: VideoStoreAPI + password: <%= ENV['VIDEOSTOREAPI_DATABASE_PASSWORD'] %> diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..426333bb4 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 000000000..abc82221c --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..3bd8115ea --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,83 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Attempt to read encrypted secrets from `config/secrets.yml.enc`. + # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or + # `config/secrets.yml.key`. + config.read_encrypted_secrets = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Mount Action Cable outside main process or domain + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "VideoStoreAPI_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..8e5cbde53 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,42 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 000000000..89d2efab2 --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb new file mode 100644 index 000000000..59385cdf3 --- /dev/null +++ b/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb new file mode 100644 index 000000000..3b1c1b5ed --- /dev/null +++ b/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..4a994e1e7 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..ac033bf9d --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb new file mode 100644 index 000000000..dc1899682 --- /dev/null +++ b/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/config/initializers/wrap_parameters.rb b/config/initializers/wrap_parameters.rb new file mode 100644 index 000000000..bbfc3961b --- /dev/null +++ b/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..decc5a857 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# 'true': 'foo' +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..1e19380dc --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,56 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# If you are preloading your application and using Active Record, it's +# recommended that you close any connections to the database before workers +# are forked to prevent connection leakage. +# +# before_fork do +# ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) +# end + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted, this block will be run. If you are using the `preload_app!` +# option, you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, as Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end +# + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..787824f88 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,3 @@ +Rails.application.routes.draw do + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html +end diff --git a/config/secrets.yml b/config/secrets.yml new file mode 100644 index 000000000..6c67ff752 --- /dev/null +++ b/config/secrets.yml @@ -0,0 +1,32 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +# Shared secrets are available across all environments. + +# shared: +# api_key: a1B2c3D4e5F6 + +# Environmental secrets are only available for that specific environment. + +development: + secret_key_base: e977e4ad787b962f9f204061b980b5e58d380b4cbcafed6a74e931ee4edc7c8a7601d10c5028a1267da134a202e96421ecadb6123767c0c7ad79294c09e79938 + +test: + secret_key_base: 07173612032624fb4b4104284ed705c96de80f4f45365b7b2cd69f845fc63bd3e2e159496500229de5e9ddc6d2774ada87db0d397d9e18e4dbe0241735f42143 + +# Do not keep production secrets in the unencrypted secrets file. +# Instead, either read values from the environment. +# Or, use `bin/rails secrets:setup` to configure encrypted secrets +# and move the `production:` environment over there. + +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/config/spring.rb b/config/spring.rb new file mode 100644 index 000000000..c9119b40c --- /dev/null +++ b/config/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/db/migrate/20180507194317_create_movies.rb b/db/migrate/20180507194317_create_movies.rb new file mode 100644 index 000000000..62885a98f --- /dev/null +++ b/db/migrate/20180507194317_create_movies.rb @@ -0,0 +1,12 @@ +class CreateMovies < ActiveRecord::Migration[5.1] + def change + create_table :movies do |t| + t.string :title + t.string :overview + t.date :release_date + t.integer :inventory + + t.timestamps + end + end +end diff --git a/db/migrate/20180507194620_create_customers.rb b/db/migrate/20180507194620_create_customers.rb new file mode 100644 index 000000000..8c89f983a --- /dev/null +++ b/db/migrate/20180507194620_create_customers.rb @@ -0,0 +1,14 @@ +class CreateCustomers < ActiveRecord::Migration[5.1] + def change + create_table :customers do |t| + t.string :name + t.string :address + t.string :city + t.string :state + t.string :postal_code + t.string :phone + + t.timestamps + end + end +end diff --git a/db/migrate/20180507194739_create_rentals.rb b/db/migrate/20180507194739_create_rentals.rb new file mode 100644 index 000000000..75ca626dd --- /dev/null +++ b/db/migrate/20180507194739_create_rentals.rb @@ -0,0 +1,13 @@ +class CreateRentals < ActiveRecord::Migration[5.1] + def change + create_table :rentals do |t| + t.datetime :due_date + t.datetime :checkout_date + t.datetime :checkin_date + t.belongs_to :customer, index: true + t.belongs_to :movie, index: true + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..bf20fbcd4 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,50 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 20180507194739) do + + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "customers", force: :cascade do |t| + t.string "name" + t.string "address" + t.string "city" + t.string "state" + t.string "postal_code" + t.string "phone" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "movies", force: :cascade do |t| + t.string "title" + t.string "overview" + t.date "release_date" + t.integer "inventory" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "rentals", force: :cascade do |t| + t.datetime "due_date" + t.datetime "checkout_date" + t.datetime "checkin_date" + t.bigint "customer_id" + t.bigint "movie_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["customer_id"], name: "index_rentals_on_customer_id" + t.index ["movie_id"], name: "index_rentals_on_movie_id" + end + +end diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..37b576a4a --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/.keep b/test/fixtures/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/customers.yml b/test/fixtures/customers.yml new file mode 100644 index 000000000..2823d1188 --- /dev/null +++ b/test/fixtures/customers.yml @@ -0,0 +1,17 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + name: MyString + address: MyString + city: MyString + state: MyString + postal_code: MyString + phone: MyString + +two: + name: MyString + address: MyString + city: MyString + state: MyString + postal_code: MyString + phone: MyString diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/rentals.yml b/test/fixtures/rentals.yml new file mode 100644 index 000000000..9100f0692 --- /dev/null +++ b/test/fixtures/rentals.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + due_date: 2018-05-07 + checkout_date: 2018-05-07 + checkin_date: 2018-05-07 + +two: + due_date: 2018-05-07 + checkout_date: 2018-05-07 + checkin_date: 2018-05-07 diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb new file mode 100644 index 000000000..5ebc5c850 --- /dev/null +++ b/test/models/customer_test.rb @@ -0,0 +1,9 @@ +require "test_helper" + +describe Customer do + let(:customer) { Customer.new } + + it "must be valid" do + value(customer).must_be :valid? + end +end diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb new file mode 100644 index 000000000..6ea53d94f --- /dev/null +++ b/test/models/rental_test.rb @@ -0,0 +1,9 @@ +require "test_helper" + +describe Rental do + let(:rental) { Rental.new } + + it "must be valid" do + value(rental).must_be :valid? + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 000000000..10594a324 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,26 @@ +ENV["RAILS_ENV"] = "test" +require File.expand_path("../../config/environment", __FILE__) +require "rails/test_help" +require "minitest/rails" +require "minitest/reporters" # for Colorized output + +# For colorful output! +Minitest::Reporters.use!( + Minitest::Reporters::SpecReporter.new, + ENV, + Minitest.backtrace_filter +) + + +# To add Capybara feature tests add `gem "minitest-rails-capybara"` +# to the test group in the Gemfile and uncomment the following: +# require "minitest/rails/capybara" + +# Uncomment for awesome colorful output +# require "minitest/pride" + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + # Add more helper methods to be used by all tests here... +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb From 844cca0c697da879946bfaadaa6a2b778bdfb171 Mon Sep 17 00:00:00 2001 From: kseastman Date: Mon, 7 May 2018 12:57:43 -0700 Subject: [PATCH 02/36] added zomg route and controlllers, verified in postman. --- app/controllers/customers_controller.rb | 4 ++++ app/controllers/movies_controller.rb | 5 +++++ config/routes.rb | 1 + test/controllers/customers_controller_test.rb | 9 +++++++++ test/controllers/movies_controller_test.rb | 7 +++++++ 5 files changed, 26 insertions(+) create mode 100644 app/controllers/customers_controller.rb create mode 100644 app/controllers/movies_controller.rb create mode 100644 test/controllers/customers_controller_test.rb create mode 100644 test/controllers/movies_controller_test.rb diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb new file mode 100644 index 000000000..73302240c --- /dev/null +++ b/app/controllers/customers_controller.rb @@ -0,0 +1,4 @@ +class CustomersController < ApplicationController + def index + end +end diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb new file mode 100644 index 000000000..3009867ea --- /dev/null +++ b/app/controllers/movies_controller.rb @@ -0,0 +1,5 @@ +class MoviesController < ApplicationController + def zomg + render json: {message: "it works!"}, status: :ok + end +end diff --git a/config/routes.rb b/config/routes.rb index 787824f88..275236aae 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,3 +1,4 @@ Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html + get '/zomg', to: 'movies#zomg' end diff --git a/test/controllers/customers_controller_test.rb b/test/controllers/customers_controller_test.rb new file mode 100644 index 000000000..c5ec6f20b --- /dev/null +++ b/test/controllers/customers_controller_test.rb @@ -0,0 +1,9 @@ +require "test_helper" + +describe CustomersController do + it "should get index" do + get customers_index_url + value(response).must_be :success? + end + +end diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb new file mode 100644 index 000000000..67fabbcfb --- /dev/null +++ b/test/controllers/movies_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +describe MoviesController do + # it "must be a real test" do + # flunk "Need real tests" + # end +end From 98863ac3b6a561139b8ebd6ec7e8b78169245217 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Mon, 7 May 2018 14:35:01 -0700 Subject: [PATCH 03/36] Controller tests and initialize methods for Customer class added. All tests passing --- .gitignore | 2 ++ Gemfile | 1 + Gemfile.lock | 8 ++++++++ app/models/customer.rb | 26 ++++++++++++++++++++++++ db/seeds.rb | 2 +- test/models/customer_test.rb | 39 +++++++++++++++++++++++++++++++++--- test/test_helper.rb | 9 ++++++++- 7 files changed, 82 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 68ac019ec..fd0838a7d 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ !/tmp/.keep .byebug_history + +coverage diff --git a/Gemfile b/Gemfile index 78bff8d26..8402773d4 100644 --- a/Gemfile +++ b/Gemfile @@ -47,4 +47,5 @@ end group :test do gem 'minitest-rails' gem 'minitest-reporters' + gem 'simplecov', require: false end diff --git a/Gemfile.lock b/Gemfile.lock index e547d2449..d936cd1e6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -45,12 +45,14 @@ GEM coderay (1.1.2) concurrent-ruby (1.0.5) crass (1.0.4) + docile (1.3.0) erubi (1.7.1) ffi (1.9.23) globalid (0.4.1) activesupport (>= 4.2.0) i18n (1.0.1) concurrent-ruby (~> 1.0) + json (2.1.0) listen (3.1.5) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) @@ -114,6 +116,11 @@ GEM ffi (>= 0.5.0, < 2) ruby-progressbar (1.9.0) ruby_dep (1.5.0) + simplecov (0.16.1) + docile (~> 1.1) + json (>= 1.8, < 3) + simplecov-html (~> 0.10.0) + simplecov-html (0.10.2) spring (2.0.2) activesupport (>= 4.2) spring-watcher-listen (2.0.1) @@ -146,6 +153,7 @@ DEPENDENCIES pry-rails puma (~> 3.7) rails (~> 5.1.6) + simplecov spring spring-watcher-listen (~> 2.0.0) tzinfo-data diff --git a/app/models/customer.rb b/app/models/customer.rb index 0b5277335..f558b1f8f 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -1,2 +1,28 @@ class Customer < ApplicationRecord + + validates :name, presence: true + + def set_registration(registration) + self.created_at = DateTime.parse(registration) + end + + def self.create_from_json(hash) + cust_data = { + name: hash["name"], + address: hash["address"], + city: hash["city"], + state: hash["state"], + postal_code: hash["postal_code"], + phone: hash["phone"], + } + + instance = self.create!(cust_data) + + if hash["registered_at"] + instance.set_registration(hash["registered_at"]) + end + return instance + end + + end diff --git a/db/seeds.rb b/db/seeds.rb index 5322340ba..f878e0762 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -1,5 +1,5 @@ JSON.parse(File.read('db/seeds/customers.json')).each do |customer| - Customer.create!(customer) + Customer.create_from_json(customer) end JSON.parse(File.read('db/seeds/movies.json')).each do |movie| diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 5ebc5c850..58ee78697 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -1,9 +1,42 @@ require "test_helper" describe Customer do - let(:customer) { Customer.new } + describe "create from json" do + it "can create a new instance from hash" do + hash = { + "name" => "Shelley Rocha", + "registered_at" => "Wed, 29 Apr 2015 07:54:14 -0700", + "address" => "Ap #292-5216 Ipsum Rd.", + "city" => "Hillsboro", + "state" => "OR", + "postal_code" => "24309", + "phone" => "(322) 510-8695" + } + expected_creation = DateTime.parse("Wed, 29 Apr 2015 07:54:14 -0700") - it "must be valid" do - value(customer).must_be :valid? + previous_count = Customer.count + result = Customer.create_from_json(hash) + result.must_be_kind_of Customer + result.name.must_equal hash["name"] + result.created_at.must_equal expected_creation + Customer.count.must_equal previous_count + 1 + end + + it "does not create a customer with incomplete data" do + hash = { + "city" => "Hillsboro", + "state" => "OR", + "postal_code" => "24309", + "phone" => "(322) 510-8695" + } + + previous_count = Customer.count + proc { + Customer.create_from_json(hash) + }.must_raise + Customer.find_by(phone: hash["phone"]).must_be_nil + Customer.count.must_equal previous_count + end end + end diff --git a/test/test_helper.rb b/test/test_helper.rb index 10594a324..5f1ae1a31 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,9 +1,16 @@ +require 'simplecov' +SimpleCov.start 'rails' do + add_filter '/bin/' + add_filter '/db/' + add_filter '/spec/' # for rspec + add_filter '/test/' # for minitest +end ENV["RAILS_ENV"] = "test" require File.expand_path("../../config/environment", __FILE__) require "rails/test_help" require "minitest/rails" require "minitest/reporters" # for Colorized output - +require "date" # For colorful output! Minitest::Reporters.use!( Minitest::Reporters::SpecReporter.new, From d63dbb8c24186351375a1a17c5df9a6fa6507157 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Mon, 7 May 2018 14:58:57 -0700 Subject: [PATCH 04/36] Add model tests for movie and make them pass with method and validations. All tests passing --- app/models/movie.rb | 12 +++++++++ test/fixtures/movies.yml | 0 test/models/movie_test.rb | 55 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 app/models/movie.rb create mode 100644 test/fixtures/movies.yml create mode 100644 test/models/movie_test.rb diff --git a/app/models/movie.rb b/app/models/movie.rb new file mode 100644 index 000000000..74c9fc545 --- /dev/null +++ b/app/models/movie.rb @@ -0,0 +1,12 @@ +class Movie < ApplicationRecord + + validates :title, presence: true + validates :inventory, :numericality => { :greater_than_or_equal_to => 0} + + def self.create_from_json(hash) + hash["release_date"] = Date.parse(hash["release_date"]) + + self.create!(hash) + + end +end diff --git a/test/fixtures/movies.yml b/test/fixtures/movies.yml new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb new file mode 100644 index 000000000..b63ba790a --- /dev/null +++ b/test/models/movie_test.rb @@ -0,0 +1,55 @@ +require "test_helper" + +describe Movie do + + describe "create from json" do + + it "creates an instance from complete hash" do + hash = { + "title" => "Blacksmith Of The Banished", + "overview" => "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", + "release_date" => "1979-01-18", + "inventory" => 10 + } + + old_count = Movie.count + result = Movie.create_from_json(hash) + result.must_be_kind_of Movie + result.title.must_equal hash["title"] + Movie.count.must_equal old_count + 1 + end + + it "doesn't create an instance with incomplete data" do + hash = { + "overview" => "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", + "release_date" => "1979-01-18", + "inventory" => 10 + } + + old_count = Movie.count + proc { + Movie.create_from_json(hash) + }.must_raise + + Movie.count.must_equal old_count + end + + it "doesn't create an instance with unacceptable data" do + hash = { + "title" => "Some Title", + "overview" => "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", + "release_date" => "1979-01-18", + "inventory" => -7 + } + + old_count = Movie.count + proc { + Movie.create_from_json(hash) + }.must_raise + + Movie.count.must_equal old_count + end + + end + +end From 728016a24e8b96b6b69d5f4bc7f860a9f736fb29 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Mon, 7 May 2018 14:59:36 -0700 Subject: [PATCH 05/36] Ready to seed --- db/seeds.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/seeds.rb b/db/seeds.rb index f878e0762..776bb4e89 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -3,5 +3,5 @@ end JSON.parse(File.read('db/seeds/movies.json')).each do |movie| - Movie.create!(movie) + Movie.create_from_json(movie) end From 508928abcc029cafdd3effe137dff63e4ca97cb1 Mon Sep 17 00:00:00 2001 From: kseastman Date: Mon, 7 May 2018 15:07:44 -0700 Subject: [PATCH 06/36] added routes and rentals controller. --- app/controllers/rentals_controller.rb | 7 +++++++ config/routes.rb | 6 ++++++ test/controllers/rentals_controller_test.rb | 14 ++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 app/controllers/rentals_controller.rb create mode 100644 test/controllers/rentals_controller_test.rb diff --git a/app/controllers/rentals_controller.rb b/app/controllers/rentals_controller.rb new file mode 100644 index 000000000..012699722 --- /dev/null +++ b/app/controllers/rentals_controller.rb @@ -0,0 +1,7 @@ +class RentalsController < ApplicationController + def checkout + end + + def checkin + end +end diff --git a/config/routes.rb b/config/routes.rb index 275236aae..0e8ca4edb 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,10 @@ Rails.application.routes.draw do + post 'rentals/checkout', to: 'rentals#checkout', as: :checkout + + post 'rentals/checkin', to: 'rentals#checkin', as: :checkin + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/zomg', to: 'movies#zomg' + resources :customers, only: [:index] + resources :movies, only: [:index, :show] end diff --git a/test/controllers/rentals_controller_test.rb b/test/controllers/rentals_controller_test.rb new file mode 100644 index 000000000..da64a7a36 --- /dev/null +++ b/test/controllers/rentals_controller_test.rb @@ -0,0 +1,14 @@ +require "test_helper" + +describe RentalsController do + it "should get checkout" do + get rentals_checkout_url + value(response).must_be :success? + end + + it "should get checkin" do + get rentals_checkin_url + value(response).must_be :success? + end + +end From b0f200df12d779f6c44f1835b0a2fc948c67f5f0 Mon Sep 17 00:00:00 2001 From: kseastman Date: Mon, 7 May 2018 16:18:45 -0700 Subject: [PATCH 07/36] created movie fixtures, tests for movies controller and customers controller, and rendering json. --- app/controllers/customers_controller.rb | 10 +++ app/controllers/movies_controller.rb | 32 +++++++- config/routes.rb | 8 +- test/controllers/customers_controller_test.rb | 43 ++++++++++- test/controllers/movies_controller_test.rb | 76 ++++++++++++++++++- test/fixtures/movies.yml | 17 +++++ 6 files changed, 177 insertions(+), 9 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 73302240c..608e1d0cc 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -1,4 +1,14 @@ class CustomersController < ApplicationController def index + customers = Customer.all + if customers.empty? + render json: {errors: { + customer: ["No customers were found"] + } + }, status: :not_found + + else + render json: customers.as_json(only: [:address, :city, :id, :name, :phone, :postal_code, :state]), status: :ok + end end end diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index 3009867ea..f08878b10 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -1,5 +1,35 @@ class MoviesController < ApplicationController + def zomg render json: {message: "it works!"}, status: :ok end -end + + def index + movies = Movie.all + + if movies.empty? + render json: { + errors: { movie: ["No Movies were found"]} + }, status: :not_found + + else + render json: movies.as_json(only: [:title, :overview, :release_date, :inventory]), status: :ok + end + end + + + def show + movie = Movie.find_by(id: params[:id]) + + if movie + render json: movie.as_json, status: :ok + else + render json: {errors: {movie: ["Cound not find movie with ID: #{params[:id]}"]}}, status: :not_found + end + end + + private + def movie_params + return params.require[:movie].permit[:title, :overview, :release_date, :inventory] + end + end diff --git a/config/routes.rb b/config/routes.rb index 0e8ca4edb..5cb1c980e 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,10 +1,12 @@ Rails.application.routes.draw do - post 'rentals/checkout', to: 'rentals#checkout', as: :checkout - post 'rentals/checkin', to: 'rentals#checkin', as: :checkin # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html - get '/zomg', to: 'movies#zomg' + resources :customers, only: [:index] resources :movies, only: [:index, :show] + + post 'rentals/checkout', to: 'rentals#checkout', as: :checkout + + post 'rentals/checkin', to: 'rentals#checkin', as: :checkin end diff --git a/test/controllers/customers_controller_test.rb b/test/controllers/customers_controller_test.rb index c5ec6f20b..6ff695cc6 100644 --- a/test/controllers/customers_controller_test.rb +++ b/test/controllers/customers_controller_test.rb @@ -2,8 +2,47 @@ describe CustomersController do it "should get index" do - get customers_index_url - value(response).must_be :success? + get customers_path + + must_respond_with :success + end + + it "returns json with collection of customers" do + get customers_path + + response.header['Content-Type'].must_include 'json' + + body = JSON.parse(response.body) + + body.must_be_kind_of Array + body.length.must_equal Customer.count + end + + it "returns with the exact fields required" do + keys = %w(address city id name phone postal_code state) + + get customers_path + body = JSON.parse(response.body) + + body.each do |customer| + customer.keys.sort!.must_equal keys + end + end + + it "returns no content when no available customers" do + Customer.destroy_all + + Customer.count.must_equal 0 + + get customers_path + + must_respond_with :not_found + puts "Here is the response body: #{response.body}" + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" + + body["errors"].must_include "customer" end end diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index 67fabbcfb..8f8c7452e 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -1,7 +1,77 @@ require "test_helper" describe MoviesController do - # it "must be a real test" do - # flunk "Need real tests" - # end + describe "movies#index" do + it "gets index" do + get movies_path + must_respond_with :success + end + + it "sends json with a collection of movies" do + get movies_path + response.header['Content-Type'].must_include 'json' + + body = JSON.parse(response.body) + + body.must_be_kind_of Array + body.length.must_equal Movie.count + end + + it "returns with the exact fields required" do + keys = %w(inventory overview release_date title ) + + get movies_path + + body = JSON.parse(response.body) + + body.each do |movie| + movie.keys.sort!.must_equal keys + end + end + + it "returns no content when no available movies" do + Movie.destroy_all + + Movie.count.must_equal 0 + + get movies_path + + must_respond_with :not_found + puts "Here is the response body: #{response.body}" + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" + + body["errors"].must_include "movie" + end + end + + describe "show " do + it "finds existant movie" do + movie = movies(:one) + + get movie_path(movie.id) + + must_respond_with :success + + response.header["Content-Type"].must_include 'json' + + body = JSON.parse(response.body) + + body.must_be_kind_of Hash + body["id"].must_equal movie.id + end + + it "responds with not found if no movie" do + movie_id = Movie.last.id + 1 + + get movie_path(movie_id) + + body = JSON.parse(response.body) + + body.must_be_kind_of Hash + body.must_include "errors" + body["errors"].must_include "movie" + end + end end diff --git a/test/fixtures/movies.yml b/test/fixtures/movies.yml index e69de29bb..b4a09f065 100644 --- a/test/fixtures/movies.yml +++ b/test/fixtures/movies.yml @@ -0,0 +1,17 @@ +one: + title: Blacksmith Of The Banished + overview: The unexciting life of a boy will be permanently altered as a strange woman enters his life. + release_date: 1979-01-18 + inventory: 10 + +two: + title: Savior Of The Curse + overview: The strange woman claims the boy has a DNA strain which very likely offers the key to cure several crippling diseases. Tests will have to be done but the key to save millions of lives is within the grasp of science through this DNA strain. Unsure what to think of all this and of this strange woman the boy hesitantly agrees to the proposal there's something exciting about this whole situation surely the right choice was made. + release_date: 2010-11-05 + inventory: 1 + +three: + title: Women Of Destruction + overview: But what if this strange woman is a con artist. Or what if everything told is completely true. How could an ordinary boy be relied upon in something this big. Time will tell. + release_date: 2006-10-01 + inventory: 1 From d0c595fdfa74b132f0af38acc576271ab17019f7 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Mon, 7 May 2018 16:49:44 -0700 Subject: [PATCH 08/36] Add controller tests for create method in movies and make them pass --- app/controllers/customers_controller.rb | 2 +- app/controllers/movies_controller.rb | 17 +++++- config/routes.rb | 2 +- test/controllers/movies_controller_test.rb | 68 +++++++++++++++++++++- 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 608e1d0cc..2de5a9674 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -8,7 +8,7 @@ def index }, status: :not_found else - render json: customers.as_json(only: [:address, :city, :id, :name, :phone, :postal_code, :state]), status: :ok + render json: customers.as_json(only: [:id, :name, :created_at, :phone, :postal_code]), status: :ok end end end diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index f08878b10..4f645c8ca 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -13,7 +13,7 @@ def index }, status: :not_found else - render json: movies.as_json(only: [:title, :overview, :release_date, :inventory]), status: :ok + render json: movies.as_json(only: [:id, :title, :release_date]), status: :ok end end @@ -28,8 +28,21 @@ def show end end + def create + movie = Movie.new(movie_params) + + if movie.save + render json: { id: movie.id }, status: :created + else + render json: { + errors: movie.errors.messages + }, status: :bad_request + end + + end + private def movie_params - return params.require[:movie].permit[:title, :overview, :release_date, :inventory] + return params.require(:movie).permit(:title, :overview, :release_date, :inventory) end end diff --git a/config/routes.rb b/config/routes.rb index 5cb1c980e..826fd7702 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,7 +4,7 @@ # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :customers, only: [:index] - resources :movies, only: [:index, :show] + resources :movies, only: [:index, :show, :create] post 'rentals/checkout', to: 'rentals#checkout', as: :checkout diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index 8f8c7452e..0df21448a 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -18,7 +18,7 @@ end it "returns with the exact fields required" do - keys = %w(inventory overview release_date title ) + keys = %w(id release_date title) get movies_path @@ -32,12 +32,11 @@ it "returns no content when no available movies" do Movie.destroy_all - Movie.count.must_equal 0 + Movie.count.must_equal 0 get movies_path must_respond_with :not_found - puts "Here is the response body: #{response.body}" body = JSON.parse(response.body) body.must_be_kind_of Hash body.must_include "errors" @@ -74,4 +73,67 @@ body["errors"].must_include "movie" end end + + describe "create" do + it "responds with ok with appropriate data" do + param_hash = { + + title: "Test movie Title", + inventory: 3 + + } + + old_count = Movie.count + post movies_path, params: { movie: param_hash } + must_respond_with :created + response.header["Content-Type"].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "id" + Movie.count.must_equal old_count + 1 + body["id"].must_equal Movie.last.id + end + + describe "responds with bad request to inappropriate data" do + it "inappropriate inventory" do + param_hash = { + movie: { + title: "Test movie Title", + inventory: -8 + } + } + + old_count = Movie.count + post movies_path, params: { movie: param_hash } + must_respond_with :bad_request + response.header["Content-Type"].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" + Movie.count.must_equal old_count + body["errors"].must_include "inventory" + end + + it "missing title" do + param_hash = { + movie: { + title: nil, + inventory: 6 + } + } + + old_count = Movie.count + post movies_path, params: { movie: param_hash } + must_respond_with :bad_request + response.header["Content-Type"].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" + Movie.count.must_equal old_count + body["errors"].must_include "title" + end + + end + + end end From b6c357cf032eb677e4d7d5bebda742f381d9b957 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Mon, 7 May 2018 17:04:04 -0700 Subject: [PATCH 09/36] begin rentals controller tests --- app/controllers/rentals_controller.rb | 2 ++ test/controllers/rentals_controller_test.rb | 14 ++++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/app/controllers/rentals_controller.rb b/app/controllers/rentals_controller.rb index 012699722..76c319d7b 100644 --- a/app/controllers/rentals_controller.rb +++ b/app/controllers/rentals_controller.rb @@ -1,7 +1,9 @@ class RentalsController < ApplicationController def checkout + end def checkin + end end diff --git a/test/controllers/rentals_controller_test.rb b/test/controllers/rentals_controller_test.rb index da64a7a36..239a5612b 100644 --- a/test/controllers/rentals_controller_test.rb +++ b/test/controllers/rentals_controller_test.rb @@ -1,14 +1,16 @@ require "test_helper" describe RentalsController do - it "should get checkout" do - get rentals_checkout_url - value(response).must_be :success? + + describe "checkout" do + it "should respond with created and rental id with apprpriate data" do + + end + end - it "should get checkin" do - get rentals_checkin_url - value(response).must_be :success? + describe "checkin" do + end end From fcc917cc1f517431461402b5fd2df6cefb1643c8 Mon Sep 17 00:00:00 2001 From: kseastman Date: Tue, 8 May 2018 10:24:33 -0700 Subject: [PATCH 10/36] rental model testing, and movie, rental and customer relationships added. --- app/models/customer.rb | 2 + app/models/movie.rb | 2 + app/models/rental.rb | 20 ++++++++++ test/models/rental_test.rb | 77 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 98 insertions(+), 3 deletions(-) diff --git a/app/models/customer.rb b/app/models/customer.rb index f558b1f8f..a7c319a39 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -1,4 +1,6 @@ class Customer < ApplicationRecord + has_many :rentals + has_many :movies, through: :rentals validates :name, presence: true diff --git a/app/models/movie.rb b/app/models/movie.rb index 74c9fc545..8773b6516 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -1,4 +1,6 @@ class Movie < ApplicationRecord + has_many :rentals + has_many :customers, through: :rentals validates :title, presence: true validates :inventory, :numericality => { :greater_than_or_equal_to => 0} diff --git a/app/models/rental.rb b/app/models/rental.rb index 79e3a65ca..1d0b8d64d 100644 --- a/app/models/rental.rb +++ b/app/models/rental.rb @@ -1,2 +1,22 @@ class Rental < ApplicationRecord + belongs_to :movie + belongs_to :customer + + def self.create_from_request(params_hash) + rental_data = { + checkout_date: DateTime.now, + due_date: DateTime.now + 7, + customer_id: params_hash[:customer_id], + movie_id: params_hash[:movie_id] + } + + rental = self.new(rental_data) + + # TODO: liked the way this worked with just return rental.save for boolean, figure it out if time? + if rental.save + return rental + else + return false + end + end end diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb index 6ea53d94f..5a2acc7c3 100644 --- a/test/models/rental_test.rb +++ b/test/models/rental_test.rb @@ -1,9 +1,80 @@ require "test_helper" describe Rental do - let(:rental) { Rental.new } + before do + @movie = Movie.first + @customer = Customer.first + end + + describe "Can be created" do + it "with valid data" do + old_rental_count = Rental.count + + rental = Rental.new(movie: @movie, customer: @customer) + + rental.must_be :valid? + rental.save + + rental.must_be_kind_of Rental + Rental.count.must_equal old_rental_count + 1 + end + end + + describe "model methods" do + describe "rental#create_from_request" do + it "creates a rental" do + checkout_date = DateTime.now + due_date = checkout_date + 7 + old_rental_count = Rental.count + + rental_data = { + customer_id: @customer.id, + movie_id: @movie.id + } + + rental = Rental.create_from_request(rental_data) + + result = (rental.due_date - due_date) + + rental.must_be_kind_of Rental + Rental.count.must_equal old_rental_count + 1 + result.must_be :<, 1 + end + + it "returns false if given invalid data" do + old_rental_count = Rental.count + rental_data = { + customer_id: nil, + movie_id: @movie.id + } + + rental = Rental.create_from_request(rental_data) + + rental.must_equal false + Rental.count.must_equal old_rental_count + end + end + + end + + describe "relationships" do + before do + @rental = Rental.create!(movie: @movie, customer: @customer) + end + + it "ties rentals and customer" do + result = @rental.customer + + result.must_be_kind_of Customer + result.id.must_equal @customer.id + end + + it "ties rentals and movies" do + result = @rental.movie + + result.must_be_kind_of Movie + result.id.must_equal @movie.id + end - it "must be valid" do - value(rental).must_be :valid? end end From dd15ea68c8cdfa1eb61837e9a8e385f0b295e65a Mon Sep 17 00:00:00 2001 From: kseastman Date: Tue, 8 May 2018 12:32:57 -0700 Subject: [PATCH 11/36] rental controller checkout tests and methods. --- app/controllers/rentals_controller.rb | 11 ++++- app/models/rental.rb | 7 +--- test/controllers/rentals_controller_test.rb | 45 ++++++++++++++++++++- test/models/rental_test.rb | 5 ++- 4 files changed, 57 insertions(+), 11 deletions(-) diff --git a/app/controllers/rentals_controller.rb b/app/controllers/rentals_controller.rb index 76c319d7b..c82858c3d 100644 --- a/app/controllers/rentals_controller.rb +++ b/app/controllers/rentals_controller.rb @@ -1,9 +1,16 @@ class RentalsController < ApplicationController def checkout - + rental = Rental.create_from_request(params) + if rental.save + render json: { id: rental.id }, status: :created + else + render json: { + errors: rental.errors.messages + }, status: :bad_request + end end def checkin - + end end diff --git a/app/models/rental.rb b/app/models/rental.rb index 1d0b8d64d..d86c2f62a 100644 --- a/app/models/rental.rb +++ b/app/models/rental.rb @@ -13,10 +13,7 @@ def self.create_from_request(params_hash) rental = self.new(rental_data) # TODO: liked the way this worked with just return rental.save for boolean, figure it out if time? - if rental.save - return rental - else - return false - end + return rental + end end diff --git a/test/controllers/rentals_controller_test.rb b/test/controllers/rentals_controller_test.rb index 239a5612b..ed3c244da 100644 --- a/test/controllers/rentals_controller_test.rb +++ b/test/controllers/rentals_controller_test.rb @@ -1,16 +1,57 @@ require "test_helper" describe RentalsController do - + before do + @customer = Customer.first + @movie = Movie.first + end describe "checkout" do - it "should respond with created and rental id with apprpriate data" do + it "should respond with created" do + post checkout_path, params: {customer_id: @customer.id, movie_id: @movie.id} + + must_respond_with :created + end + + it "should respond with rental id given valid data" do + rental = { + customer_id: @customer.id, + movie_id: @movie.id + } + + post checkout_path, params: rental + + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include 'id' + body['id'].must_equal Rental.last.id + end + + it "should respond with bad_request and error text given invalid data" do + rental = { + customer_id: nil, + movie_id: @movie.id + } + + post checkout_path, params: rental + must_respond_with :bad_request + + + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include 'errors' + body['errors'].must_include 'customer' end + end describe "checkin" do + it "should respond with success" do + end end end diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb index 5a2acc7c3..64ab30143 100644 --- a/test/models/rental_test.rb +++ b/test/models/rental_test.rb @@ -33,6 +33,7 @@ } rental = Rental.create_from_request(rental_data) + rental.save result = (rental.due_date - due_date) @@ -41,7 +42,7 @@ result.must_be :<, 1 end - it "returns false if given invalid data" do + it "returns invalid rental if given invalid data" do old_rental_count = Rental.count rental_data = { customer_id: nil, @@ -50,7 +51,7 @@ rental = Rental.create_from_request(rental_data) - rental.must_equal false + rental.wont_be :valid? Rental.count.must_equal old_rental_count end end From 9805f248ada0612527d12a1fab940a1c5aec8366 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Tue, 8 May 2018 13:01:37 -0700 Subject: [PATCH 12/36] rentals controller tests created. Tests now passing with json rendered and statuses --- app/controllers/rentals_controller.rb | 24 +++++++++++-- test/controllers/rentals_controller_test.rb | 40 +++++++++++++++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/app/controllers/rentals_controller.rb b/app/controllers/rentals_controller.rb index c82858c3d..85a45483e 100644 --- a/app/controllers/rentals_controller.rb +++ b/app/controllers/rentals_controller.rb @@ -7,10 +7,28 @@ def checkout render json: { errors: rental.errors.messages }, status: :bad_request + end end - end - def checkin + def checkin + rental = Rental.find_by(id: params[:rental_id]) + + if rental + rental.checkin_date = DateTime.now + if rental.save + render json: rental.as_json, status: :ok + else + render json: { + errors: rental.errors.messages + }, status: :bad_request + end + else + render json: { + errors: { + rental: ["Rental not found"] + } + }, status: :not_found + end + end end -end diff --git a/test/controllers/rentals_controller_test.rb b/test/controllers/rentals_controller_test.rb index ed3c244da..75d019d81 100644 --- a/test/controllers/rentals_controller_test.rb +++ b/test/controllers/rentals_controller_test.rb @@ -49,9 +49,49 @@ end describe "checkin" do + + before do + rental_data = { movie_id: Movie.first.id, customer_id: Customer.first.id } + @rental = Rental.create_from_request(rental_data) + @rental.save + end + it "should respond with success" do + post checkin_path, params: { rental_id: @rental.id } + + must_respond_with :success + end + + it "should respond with json of rental details" do + keys = %w(checkin_date checkout_date created_at customer_id due_date id movie_id updated_at) + + post checkin_path, params: { rental_id: @rental.id } + + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + + + body.keys.sort!.must_equal keys end + + it "should respond with bad_request and error text if unable to checkin" do + rental_id = Rental.last.id + 1 + + post checkin_path, params: { rental_id: rental_id} + + must_respond_with :not_found + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include 'errors' + + end + + + + end end From 59bf86859c478b6f6e4baef38d7a940d7d94d3aa Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Tue, 8 May 2018 14:31:10 -0700 Subject: [PATCH 13/36] refactor movies controller and tests to match smoke test --- app/controllers/movies_controller.rb | 2 +- test/controllers/customers_controller_test.rb | 2 +- test/controllers/movies_controller_test.rb | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index 4f645c8ca..b68cd791f 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -43,6 +43,6 @@ def create private def movie_params - return params.require(:movie).permit(:title, :overview, :release_date, :inventory) + return params.permit(:title, :overview, :release_date, :inventory) end end diff --git a/test/controllers/customers_controller_test.rb b/test/controllers/customers_controller_test.rb index 6ff695cc6..8b2d7602b 100644 --- a/test/controllers/customers_controller_test.rb +++ b/test/controllers/customers_controller_test.rb @@ -19,7 +19,7 @@ end it "returns with the exact fields required" do - keys = %w(address city id name phone postal_code state) + keys = %w(created_at id name phone postal_code) get customers_path body = JSON.parse(response.body) diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index 0df21448a..b33d160a5 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -84,7 +84,7 @@ } old_count = Movie.count - post movies_path, params: { movie: param_hash } + post movies_path, params: param_hash must_respond_with :created response.header["Content-Type"].must_include 'json' body = JSON.parse(response.body) @@ -104,7 +104,7 @@ } old_count = Movie.count - post movies_path, params: { movie: param_hash } + post movies_path, params: param_hash must_respond_with :bad_request response.header["Content-Type"].must_include 'json' body = JSON.parse(response.body) @@ -123,7 +123,7 @@ } old_count = Movie.count - post movies_path, params: { movie: param_hash } + post movies_path, params: param_hash must_respond_with :bad_request response.header["Content-Type"].must_include 'json' body = JSON.parse(response.body) From c5145d2f51ecf78d2299789086a60c7c4ab8ac6b Mon Sep 17 00:00:00 2001 From: kseastman Date: Tue, 8 May 2018 14:32:16 -0700 Subject: [PATCH 14/36] added .DS_Store to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index fd0838a7d..f0a576036 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ .byebug_history coverage +.DS_Store From e0cd8f9d23c9290eeb7bd625ccf3109d507826f0 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Tue, 8 May 2018 14:36:34 -0700 Subject: [PATCH 15/36] More refactor to pass smoke tests --- app/controllers/movies_controller.rb | 2 +- config/routes.rb | 4 ++-- test/controllers/movies_controller_test.rb | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index b68cd791f..d9cb60f73 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -32,7 +32,7 @@ def create movie = Movie.new(movie_params) if movie.save - render json: { id: movie.id }, status: :created + render json: { id: movie.id }, status: :ok else render json: { errors: movie.errors.messages diff --git a/config/routes.rb b/config/routes.rb index 826fd7702..7e0feaa01 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -6,7 +6,7 @@ resources :customers, only: [:index] resources :movies, only: [:index, :show, :create] - post 'rentals/checkout', to: 'rentals#checkout', as: :checkout + post 'rentals/check-out', to: 'rentals#checkout', as: :checkout - post 'rentals/checkin', to: 'rentals#checkin', as: :checkin + post 'rentals/check-in', to: 'rentals#checkin', as: :checkin end diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index b33d160a5..8514f985d 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -85,7 +85,7 @@ old_count = Movie.count post movies_path, params: param_hash - must_respond_with :created + must_respond_with :ok response.header["Content-Type"].must_include 'json' body = JSON.parse(response.body) body.must_be_kind_of Hash From 5488cad9f1ae245508cb85d6b7922821a4dbdacb Mon Sep 17 00:00:00 2001 From: kseastman Date: Tue, 8 May 2018 17:04:06 -0700 Subject: [PATCH 16/36] finished refactor to meet smoke test, redid controller_testing. --- app/controllers/rentals_controller.rb | 13 ++++++++++--- test/controllers/rentals_controller_test.rb | 14 ++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/app/controllers/rentals_controller.rb b/app/controllers/rentals_controller.rb index 85a45483e..1c6fe939d 100644 --- a/app/controllers/rentals_controller.rb +++ b/app/controllers/rentals_controller.rb @@ -1,8 +1,10 @@ class RentalsController < ApplicationController + # protect_from_forgery with: :null_session + def checkout - rental = Rental.create_from_request(params) + rental = Rental.create_from_request(rental_params) if rental.save - render json: { id: rental.id }, status: :created + render json: { id: rental.id }, status: :ok else render json: { errors: rental.errors.messages @@ -11,7 +13,7 @@ def checkout end def checkin - rental = Rental.find_by(id: params[:rental_id]) + rental = Rental.where(rental_params).last if rental rental.checkin_date = DateTime.now @@ -31,4 +33,9 @@ def checkin end end + + private + def rental_params + return params.permit(:customer_id, :movie_id) + end end diff --git a/test/controllers/rentals_controller_test.rb b/test/controllers/rentals_controller_test.rb index 75d019d81..0e6831e1d 100644 --- a/test/controllers/rentals_controller_test.rb +++ b/test/controllers/rentals_controller_test.rb @@ -9,7 +9,7 @@ it "should respond with created" do post checkout_path, params: {customer_id: @customer.id, movie_id: @movie.id} - must_respond_with :created + must_respond_with :ok end it "should respond with rental id given valid data" do @@ -51,13 +51,13 @@ describe "checkin" do before do - rental_data = { movie_id: Movie.first.id, customer_id: Customer.first.id } + rental_data = { movie_id: Movie.first.id, customer_id: Customer.last.id } @rental = Rental.create_from_request(rental_data) @rental.save end it "should respond with success" do - post checkin_path, params: { rental_id: @rental.id } + post checkin_path, params: { customer_id: @rental.customer.id, movie_id: @rental.movie.id } must_respond_with :success end @@ -65,7 +65,7 @@ it "should respond with json of rental details" do keys = %w(checkin_date checkout_date created_at customer_id due_date id movie_id updated_at) - post checkin_path, params: { rental_id: @rental.id } + post checkin_path, params: { customer_id: @rental.customer.id, movie_id: @rental.movie.id } response.header['Content-Type'].must_include 'json' body = JSON.parse(response.body) @@ -77,9 +77,11 @@ end it "should respond with bad_request and error text if unable to checkin" do - rental_id = Rental.last.id + 1 + params = { + customer_id: "car" + } - post checkin_path, params: { rental_id: rental_id} + post checkin_path, params: params must_respond_with :not_found response.header['Content-Type'].must_include 'json' From aa47296030ed04b08e0bbec836976e5c7b3861ce Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Tue, 8 May 2018 17:26:01 -0700 Subject: [PATCH 17/36] Add logic for rented count for customer and checked out for movie --- app/models/customer.rb | 9 +++++++++ app/models/movie.rb | 6 ++++++ test/models/customer_test.rb | 28 ++++++++++++++++++++++++++++ test/models/movie_test.rb | 28 ++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+) diff --git a/app/models/customer.rb b/app/models/customer.rb index a7c319a39..1f6fc6346 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -26,5 +26,14 @@ def self.create_from_json(hash) return instance end + def checkedout + rentals = Rental.where(customer_id: self.id) + rented_count = rentals.select{ |ren| !ren.checkin_date }.count + return rented_count + + + + end + end diff --git a/app/models/movie.rb b/app/models/movie.rb index 8773b6516..fa4b4e394 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -9,6 +9,12 @@ def self.create_from_json(hash) hash["release_date"] = Date.parse(hash["release_date"]) self.create!(hash) + end + def available + rentals = Rental.where(movie_id: self.id) + rented = rentals.select{ |rent| !rent.checkin_date }.count + avail = (self.inventory - rented) + return avail end end diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 58ee78697..99bc9fc4f 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -39,4 +39,32 @@ end end + describe "#checkedout" do + before do + @customer = Customer.first + @movie = Movie.first + end + + it "returns an integer of available inventory" do + result = @customer.checkedout + result.must_be_kind_of Integer + end + + it "updates when checkout and checkin" do + original_checkedout = @customer.checkedout + + rental = Rental.create_from_request(movie_id: @movie.id, customer_id: @customer.id) + rental.save + + result = @customer.checkedout + result.must_equal original_checkedout + 1 + + rental.checkin_date = DateTime.now + rental.save + + new_result = @customer.checkedout + new_result.must_equal original_checkedout + end + end + end diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index b63ba790a..f2033770c 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -52,4 +52,32 @@ end + describe "#available" do + before do + @movie = Movie.first + @customer = Customer.first + end + it "returns an integer of available inventory" do + result = @movie.available + result.must_be_kind_of Integer + end + + it "updates when checkout and checkin" do + original_avail = @movie.available + + rental = Rental.create_from_request(movie_id: @movie.id, customer_id: @customer.id) + rental.save + + result = @movie.available + result.must_equal original_avail - 1 + + rental.checkin_date = DateTime.now + rental.save + + new_result = @movie.available + new_result.must_equal original_avail + end + + end + end From d42176646bdddfb4469638871919234fd8c30154 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 09:21:49 -0700 Subject: [PATCH 18/36] added filters to coverage, put zomg path back in so we could test it because it's part of the assignment and we thought it was cute. --- config/routes.rb | 3 +- test/controllers/movies_controller_test.rb | 194 +++++++++++---------- test/test_helper.rb | 3 + 3 files changed, 105 insertions(+), 95 deletions(-) diff --git a/config/routes.rb b/config/routes.rb index 7e0feaa01..66695cb6a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,8 +1,7 @@ Rails.application.routes.draw do - + get '/movies/zomg', to: 'movies#zomg', as: :zomg # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html - resources :customers, only: [:index] resources :movies, only: [:index, :show, :create] diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index 8514f985d..4245e31e9 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -1,139 +1,147 @@ require "test_helper" describe MoviesController do - describe "movies#index" do - it "gets index" do - get movies_path - must_respond_with :success - end + describe 'movies#zomg' do + it "responds with ok" do + get zomg_path - it "sends json with a collection of movies" do - get movies_path - response.header['Content-Type'].must_include 'json' + must_respond_with :ok + end +end - body = JSON.parse(response.body) +describe "movies#index" do + it "gets index" do + get movies_path + must_respond_with :success + end - body.must_be_kind_of Array - body.length.must_equal Movie.count - end + it "sends json with a collection of movies" do + get movies_path + response.header['Content-Type'].must_include 'json' - it "returns with the exact fields required" do - keys = %w(id release_date title) + body = JSON.parse(response.body) - get movies_path + body.must_be_kind_of Array + body.length.must_equal Movie.count + end - body = JSON.parse(response.body) + it "returns with the exact fields required" do + keys = %w(id release_date title) + + get movies_path - body.each do |movie| - movie.keys.sort!.must_equal keys - end + body = JSON.parse(response.body) + + body.each do |movie| + movie.keys.sort!.must_equal keys end + end - it "returns no content when no available movies" do - Movie.destroy_all + it "returns no content when no available movies" do + Movie.destroy_all - Movie.count.must_equal 0 + Movie.count.must_equal 0 - get movies_path + get movies_path - must_respond_with :not_found - body = JSON.parse(response.body) - body.must_be_kind_of Hash - body.must_include "errors" + must_respond_with :not_found + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" - body["errors"].must_include "movie" - end + body["errors"].must_include "movie" end +end - describe "show " do - it "finds existant movie" do - movie = movies(:one) +describe "show " do + it "finds existant movie" do + movie = movies(:one) - get movie_path(movie.id) + get movie_path(movie.id) - must_respond_with :success + must_respond_with :success - response.header["Content-Type"].must_include 'json' + response.header["Content-Type"].must_include 'json' - body = JSON.parse(response.body) + body = JSON.parse(response.body) - body.must_be_kind_of Hash - body["id"].must_equal movie.id - end + body.must_be_kind_of Hash + body["id"].must_equal movie.id + end - it "responds with not found if no movie" do - movie_id = Movie.last.id + 1 + it "responds with not found if no movie" do + movie_id = Movie.last.id + 1 - get movie_path(movie_id) + get movie_path(movie_id) - body = JSON.parse(response.body) + body = JSON.parse(response.body) - body.must_be_kind_of Hash - body.must_include "errors" - body["errors"].must_include "movie" - end + body.must_be_kind_of Hash + body.must_include "errors" + body["errors"].must_include "movie" end +end - describe "create" do - it "responds with ok with appropriate data" do - param_hash = { +describe "create" do + it "responds with ok with appropriate data" do + param_hash = { + + title: "Test movie Title", + inventory: 3 + + } - title: "Test movie Title", - inventory: 3 + old_count = Movie.count + post movies_path, params: param_hash + must_respond_with :ok + response.header["Content-Type"].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "id" + Movie.count.must_equal old_count + 1 + body["id"].must_equal Movie.last.id + end + describe "responds with bad request to inappropriate data" do + it "inappropriate inventory" do + param_hash = { + movie: { + title: "Test movie Title", + inventory: -8 + } } old_count = Movie.count post movies_path, params: param_hash - must_respond_with :ok + must_respond_with :bad_request response.header["Content-Type"].must_include 'json' body = JSON.parse(response.body) body.must_be_kind_of Hash - body.must_include "id" - Movie.count.must_equal old_count + 1 - body["id"].must_equal Movie.last.id + body.must_include "errors" + Movie.count.must_equal old_count + body["errors"].must_include "inventory" end - describe "responds with bad request to inappropriate data" do - it "inappropriate inventory" do - param_hash = { - movie: { - title: "Test movie Title", - inventory: -8 - } - } - - old_count = Movie.count - post movies_path, params: param_hash - must_respond_with :bad_request - response.header["Content-Type"].must_include 'json' - body = JSON.parse(response.body) - body.must_be_kind_of Hash - body.must_include "errors" - Movie.count.must_equal old_count - body["errors"].must_include "inventory" - end - - it "missing title" do - param_hash = { - movie: { - title: nil, - inventory: 6 - } + it "missing title" do + param_hash = { + movie: { + title: nil, + inventory: 6 } + } - old_count = Movie.count - post movies_path, params: param_hash - must_respond_with :bad_request - response.header["Content-Type"].must_include 'json' - body = JSON.parse(response.body) - body.must_be_kind_of Hash - body.must_include "errors" - Movie.count.must_equal old_count - body["errors"].must_include "title" - end - + old_count = Movie.count + post movies_path, params: param_hash + must_respond_with :bad_request + response.header["Content-Type"].must_include 'json' + body = JSON.parse(response.body) + body.must_be_kind_of Hash + body.must_include "errors" + Movie.count.must_equal old_count + body["errors"].must_include "title" end end + +end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 5f1ae1a31..5e2ed0b29 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -4,6 +4,9 @@ add_filter '/db/' add_filter '/spec/' # for rspec add_filter '/test/' # for minitest + add_filter '/mailers/' + add_filter '/jobs/' + add_filter '/channels/' end ENV["RAILS_ENV"] = "test" require File.expand_path("../../config/environment", __FILE__) From 5b0e7ecdcac5b44553b313d2f46f913d0fa30cff Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 09:25:54 -0700 Subject: [PATCH 19/36] added rabl, oj and jbuilder to Gemfile --- Gemfile | 3 +++ Gemfile.lock | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/Gemfile b/Gemfile index 8402773d4..e3a44df9f 100644 --- a/Gemfile +++ b/Gemfile @@ -24,6 +24,9 @@ gem 'puma', '~> 3.7' # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible # gem 'rack-cors' +gem 'rabl' +gem 'oj' +gem 'jbuilder', '~> 2.5' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console diff --git a/Gemfile.lock b/Gemfile.lock index d936cd1e6..0468ac62a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -52,6 +52,9 @@ GEM activesupport (>= 4.2.0) i18n (1.0.1) concurrent-ruby (~> 1.0) + jbuilder (2.7.0) + activesupport (>= 4.2.0) + multi_json (>= 1.2) json (2.1.0) listen (3.1.5) rb-fsevent (~> 0.9, >= 0.9.4) @@ -74,9 +77,11 @@ GEM builder minitest (>= 5.0) ruby-progressbar + multi_json (1.13.1) nio4r (2.3.1) nokogiri (1.8.2) mini_portile2 (~> 2.3.0) + oj (3.6.0) pg (1.0.0) pry (0.11.3) coderay (~> 1.1.0) @@ -84,6 +89,8 @@ GEM pry-rails (0.3.6) pry (>= 0.10.4) puma (3.11.4) + rabl (0.13.1) + activesupport (>= 2.3.14) rack (2.0.5) rack-test (1.0.0) rack (>= 1.0, < 3) @@ -146,12 +153,15 @@ PLATFORMS DEPENDENCIES byebug + jbuilder (~> 2.5) listen (>= 3.0.5, < 3.2) minitest-rails minitest-reporters + oj pg (>= 0.18, < 2.0) pry-rails puma (~> 3.7) + rabl rails (~> 5.1.6) simplecov spring From 08a296775b93246a38b3faf6d342f1f89e71b67c Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Wed, 9 May 2018 09:42:57 -0700 Subject: [PATCH 20/36] adding rabl file for customer index. Refactor tests. all passing. --- app/controllers/customers_controller.rb | 7 ++++--- app/models/customer.rb | 4 ---- app/views/customers/index.json.rabl | 6 ++++++ config/initializers/rabl_config.rb | 3 +++ test/controllers/customers_controller_test.rb | 2 +- 5 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 app/views/customers/index.json.rabl create mode 100644 config/initializers/rabl_config.rb diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 2de5a9674..71f992f2d 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -1,14 +1,15 @@ class CustomersController < ApplicationController def index - customers = Customer.all - if customers.empty? + @customers = Customer.all + if @customers.empty? render json: {errors: { customer: ["No customers were found"] } }, status: :not_found else - render json: customers.as_json(only: [:id, :name, :created_at, :phone, :postal_code]), status: :ok + render 'index.json' + # render json: customers.as_json(only: [:id, :name, :created_at, :phone, :postal_code]), status: :ok end end end diff --git a/app/models/customer.rb b/app/models/customer.rb index 1f6fc6346..0c7b66892 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -30,10 +30,6 @@ def checkedout rentals = Rental.where(customer_id: self.id) rented_count = rentals.select{ |ren| !ren.checkin_date }.count return rented_count - - - end - end diff --git a/app/views/customers/index.json.rabl b/app/views/customers/index.json.rabl new file mode 100644 index 000000000..89e683ed6 --- /dev/null +++ b/app/views/customers/index.json.rabl @@ -0,0 +1,6 @@ +collection @customers + +attributes :id, :name, :phone, :postal_code +attribute :created_at => :registered_at + +node (:movies_checked_out_count) { |customer| customer.checkedout } diff --git a/config/initializers/rabl_config.rb b/config/initializers/rabl_config.rb new file mode 100644 index 000000000..f11eb190d --- /dev/null +++ b/config/initializers/rabl_config.rb @@ -0,0 +1,3 @@ +Rabl.configure do |config| + config.include_json_root = false +end diff --git a/test/controllers/customers_controller_test.rb b/test/controllers/customers_controller_test.rb index 8b2d7602b..b4d7e0ab9 100644 --- a/test/controllers/customers_controller_test.rb +++ b/test/controllers/customers_controller_test.rb @@ -19,7 +19,7 @@ end it "returns with the exact fields required" do - keys = %w(created_at id name phone postal_code) + keys = %w( id movies_checked_out_count name phone postal_code registered_at) get customers_path body = JSON.parse(response.body) From c80e70b2b7647059ecfb9e1833609baad43995c2 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 09:54:27 -0700 Subject: [PATCH 21/36] Added show and index for movies, refactored tests. All smoke tests and rails tests passing. --- app/controllers/movies_controller.rb | 12 ++++++------ app/views/movies/index.json.rabl | 3 +++ app/views/movies/show.json.rabl | 5 +++++ test/controllers/movies_controller_test.rb | 2 +- 4 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 app/views/movies/index.json.rabl create mode 100644 app/views/movies/show.json.rabl diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index d9cb60f73..fc79d76c8 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -5,24 +5,24 @@ def zomg end def index - movies = Movie.all + @movies = Movie.all - if movies.empty? + if @movies.empty? render json: { errors: { movie: ["No Movies were found"]} }, status: :not_found else - render json: movies.as_json(only: [:id, :title, :release_date]), status: :ok + render 'index.json' end end def show - movie = Movie.find_by(id: params[:id]) + @movie = Movie.find_by(id: params[:id]) - if movie - render json: movie.as_json, status: :ok + if @movie + render 'show.json' else render json: {errors: {movie: ["Cound not find movie with ID: #{params[:id]}"]}}, status: :not_found end diff --git a/app/views/movies/index.json.rabl b/app/views/movies/index.json.rabl new file mode 100644 index 000000000..7b4e21376 --- /dev/null +++ b/app/views/movies/index.json.rabl @@ -0,0 +1,3 @@ +collection @movies + +extends 'movies/show' diff --git a/app/views/movies/show.json.rabl b/app/views/movies/show.json.rabl new file mode 100644 index 000000000..127dbf3ae --- /dev/null +++ b/app/views/movies/show.json.rabl @@ -0,0 +1,5 @@ +object @movie + +attributes :id, :title, :release_date, :overview, :inventory + +node(:available_inventory) { |movie| movie.available} diff --git a/test/controllers/movies_controller_test.rb b/test/controllers/movies_controller_test.rb index 4245e31e9..e40afbc6f 100644 --- a/test/controllers/movies_controller_test.rb +++ b/test/controllers/movies_controller_test.rb @@ -26,7 +26,7 @@ end it "returns with the exact fields required" do - keys = %w(id release_date title) + keys = %w(available_inventory id inventory overview release_date title) get movies_path From d45722958aac1469d16e7111a12071b3b5abe875 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 11:08:26 -0700 Subject: [PATCH 22/36] Added rental model tests for not allowing duplicate checkouts or checkouts with no inventory. --- test/models/rental_test.rb | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb index 64ab30143..4ac5f08c0 100644 --- a/test/models/rental_test.rb +++ b/test/models/rental_test.rb @@ -78,4 +78,57 @@ end end + + describe "validations" do + before do + @movie = Movie.first + @customer = Customer.first + end + + it "cannot be created if movie.available is less than 0" do + available_inventory = @movie.available + + available_inventory.times do + customer = Customer.create!(name: "Test Customer") + rental = Rental.new(customer: customer, movie: @movie) + + rental.must_be :valid? + + rental.save + end + old_rental_count = Rental.count + rental = Rental.new(customer: @customer, movie: @movie) + + rental.wont_be :valid? + + proc { rental.save }.must_raise + rental.errors.messages.wont_be :empty? + Rental.count.must_equal old_rental_count + + end + + it "returns an ArgumentError if the customer and movie have an active rental" do + Rental.create!(customer: @customer, movie: @movie) + + rental = Rental.new(customer: @customer, movie: @movie) + rental.wont_be :valid? + + old_rental_count = Rental.count + + proc { rental.save }.must_raise + rental.errors.messages.wont_be :empty? + Rental.count.must_equal old_rental_count + end + + it "does not prevent duplicate rentals if previous rental resolved" do + rental = Rental.create!(customer: @customer, movie: @movie) + + rental.checkin_date = DateTime.now + rental.save + + second_rental = Rental.new(customer: @customer, movie: @movie) + + second_rental.must_be :valid? + end + end end From cdffa75ec0e87f9886f0f193767105f8ab52b5a3 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Wed, 9 May 2018 15:09:48 -0700 Subject: [PATCH 23/36] adding validations to make tests pass for rental model --- app/models/customer.rb | 2 +- app/models/movie.rb | 2 +- app/models/rental.rb | 30 ++++++++++++++++++++++++++++++ db/seeds.rb | 4 ++-- test/fixtures/movies.yml | 4 ++-- test/models/customer_test.rb | 4 ++-- test/models/movie_test.rb | 6 +++--- test/models/rental_test.rb | 10 +++++----- 8 files changed, 46 insertions(+), 16 deletions(-) diff --git a/app/models/customer.rb b/app/models/customer.rb index 0c7b66892..aac1b8d04 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -8,7 +8,7 @@ def set_registration(registration) self.created_at = DateTime.parse(registration) end - def self.create_from_json(hash) + def self.create_from_request(hash) cust_data = { name: hash["name"], address: hash["address"], diff --git a/app/models/movie.rb b/app/models/movie.rb index fa4b4e394..2fcfaccad 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -5,7 +5,7 @@ class Movie < ApplicationRecord validates :title, presence: true validates :inventory, :numericality => { :greater_than_or_equal_to => 0} - def self.create_from_json(hash) + def self.create_from_request(hash) hash["release_date"] = Date.parse(hash["release_date"]) self.create!(hash) diff --git a/app/models/rental.rb b/app/models/rental.rb index d86c2f62a..a095b428c 100644 --- a/app/models/rental.rb +++ b/app/models/rental.rb @@ -1,6 +1,36 @@ +class RentalValidator < ActiveModel::Validator + + def validate(record) + + if duplicate_rental(record) + record.errors.add(:base, "Customer has not returned this movie yet.") + end + + if no_availability(record) + record.errors.add(:base, "No copies of this movie are currently available") + end + + end + + private + + def duplicate_rental(record) + active_previous_rental = Rental.find_by(customer_id: record.customer_id, movie_id: record.movie_id, checkin_date: nil) + return active_previous_rental + end + + def no_availability(record) + return record.movie.available == 0 + end + +end + + + class Rental < ApplicationRecord belongs_to :movie belongs_to :customer + validates_with RentalValidator, on: :create def self.create_from_request(params_hash) rental_data = { diff --git a/db/seeds.rb b/db/seeds.rb index 776bb4e89..c3f5fe999 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -1,7 +1,7 @@ JSON.parse(File.read('db/seeds/customers.json')).each do |customer| - Customer.create_from_json(customer) + Customer.create_from_request(customer) end JSON.parse(File.read('db/seeds/movies.json')).each do |movie| - Movie.create_from_json(movie) + Movie.create_from_request(movie) end diff --git a/test/fixtures/movies.yml b/test/fixtures/movies.yml index b4a09f065..9107042c5 100644 --- a/test/fixtures/movies.yml +++ b/test/fixtures/movies.yml @@ -8,10 +8,10 @@ two: title: Savior Of The Curse overview: The strange woman claims the boy has a DNA strain which very likely offers the key to cure several crippling diseases. Tests will have to be done but the key to save millions of lives is within the grasp of science through this DNA strain. Unsure what to think of all this and of this strange woman the boy hesitantly agrees to the proposal there's something exciting about this whole situation surely the right choice was made. release_date: 2010-11-05 - inventory: 1 + inventory: 10 three: title: Women Of Destruction overview: But what if this strange woman is a con artist. Or what if everything told is completely true. How could an ordinary boy be relied upon in something this big. Time will tell. release_date: 2006-10-01 - inventory: 1 + inventory: 10 diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 99bc9fc4f..9834b334e 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -15,7 +15,7 @@ expected_creation = DateTime.parse("Wed, 29 Apr 2015 07:54:14 -0700") previous_count = Customer.count - result = Customer.create_from_json(hash) + result = Customer.create_from_request(hash) result.must_be_kind_of Customer result.name.must_equal hash["name"] result.created_at.must_equal expected_creation @@ -32,7 +32,7 @@ previous_count = Customer.count proc { - Customer.create_from_json(hash) + Customer.create_from_request(hash) }.must_raise Customer.find_by(phone: hash["phone"]).must_be_nil Customer.count.must_equal previous_count diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index f2033770c..e494cb134 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -13,7 +13,7 @@ } old_count = Movie.count - result = Movie.create_from_json(hash) + result = Movie.create_from_request(hash) result.must_be_kind_of Movie result.title.must_equal hash["title"] Movie.count.must_equal old_count + 1 @@ -28,7 +28,7 @@ old_count = Movie.count proc { - Movie.create_from_json(hash) + Movie.create_from_request(hash) }.must_raise Movie.count.must_equal old_count @@ -44,7 +44,7 @@ old_count = Movie.count proc { - Movie.create_from_json(hash) + Movie.create_from_request(hash) }.must_raise Movie.count.must_equal old_count diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb index 4ac5f08c0..1615e5eb8 100644 --- a/test/models/rental_test.rb +++ b/test/models/rental_test.rb @@ -3,7 +3,7 @@ describe Rental do before do @movie = Movie.first - @customer = Customer.first + @customer = Customer.last end describe "Can be created" do @@ -45,7 +45,7 @@ it "returns invalid rental if given invalid data" do old_rental_count = Rental.count rental_data = { - customer_id: nil, + customer_id: @customer.id + 1, movie_id: @movie.id } @@ -101,13 +101,13 @@ rental.wont_be :valid? - proc { rental.save }.must_raise + rental.save rental.errors.messages.wont_be :empty? Rental.count.must_equal old_rental_count end - it "returns an ArgumentError if the customer and movie have an active rental" do + it "doesn't update database if the customer and movie have an active rental" do Rental.create!(customer: @customer, movie: @movie) rental = Rental.new(customer: @customer, movie: @movie) @@ -115,7 +115,7 @@ old_rental_count = Rental.count - proc { rental.save }.must_raise + rental.save rental.errors.messages.wont_be :empty? Rental.count.must_equal old_rental_count end From 5216b6dc47cd8df04b6899068a7c39b771fcc7d1 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 15:11:06 -0700 Subject: [PATCH 24/36] executive decision to not refactor on our TODO note. --- app/models/rental.rb | 3 --- 1 file changed, 3 deletions(-) diff --git a/app/models/rental.rb b/app/models/rental.rb index a095b428c..b7cd8baeb 100644 --- a/app/models/rental.rb +++ b/app/models/rental.rb @@ -42,8 +42,5 @@ def self.create_from_request(params_hash) rental = self.new(rental_data) - # TODO: liked the way this worked with just return rental.save for boolean, figure it out if time? - return rental - end end From 7db4ac344ca18317f8229df46cc1b4faffb504d6 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 16:10:41 -0700 Subject: [PATCH 25/36] added customers to yaml and controller tests for optional query parameters. --- app/controllers/customers_controller.rb | 2 +- test/controllers/customers_controller_test.rb | 56 ++++++++++++++++- test/fixtures/customers.yml | 61 +++++++++++++++---- 3 files changed, 104 insertions(+), 15 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 71f992f2d..c5cfe7c6f 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -9,7 +9,7 @@ def index else render 'index.json' - # render json: customers.as_json(only: [:id, :name, :created_at, :phone, :postal_code]), status: :ok end end + end diff --git a/test/controllers/customers_controller_test.rb b/test/controllers/customers_controller_test.rb index b4d7e0ab9..e0f80f2cf 100644 --- a/test/controllers/customers_controller_test.rb +++ b/test/controllers/customers_controller_test.rb @@ -32,7 +32,7 @@ it "returns no content when no available customers" do Customer.destroy_all - Customer.count.must_equal 0 + Customer.count.must_equal 0 get customers_path @@ -45,4 +45,58 @@ body["errors"].must_include "customer" end + it "returns sorted json when given sort as parameter" do + get customers_path, params: {sort: "name"} + + must_respond_with :success + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + + body.must_be_kind_of Array + + names = body.map { |customer| customer["name"] } + + sorted_names = names.sort + + + sorted_names.must_equal names + end + + it "returns a maximum number of json records when given n as parameter" do + #if this doesn't work on implementation try a string for number + get customers_path, params: {n: "5"} + + must_respond_with :success + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + + body.must_be_kind_of Array + body.length.must_be :<=, 5 + end + + it "returns a specific page of responses when given p as a parameter" do + get customers_path, params: {p: "2"} + + must_respond_with :success + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + + body.must_be_kind_of Array + body.length.must_equal 3 + end + + it "can be successfully combined: /?sort=name&n=10&p=2" do + get customers_path, params: {sort: "name", n: "10", p: "2"} + + must_respond_with :success + response.header['Content-Type'].must_include 'json' + body = JSON.parse(response.body) + + body.must_be_kind_of Array + + names = body.map { |customer| customer["name"] } + + sorted_names = names.sort + sorted_names.must_equal names + end end diff --git a/test/fixtures/customers.yml b/test/fixtures/customers.yml index 2823d1188..750aa70e6 100644 --- a/test/fixtures/customers.yml +++ b/test/fixtures/customers.yml @@ -1,17 +1,52 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: - name: MyString - address: MyString - city: MyString - state: MyString - postal_code: MyString - phone: MyString + name: Shelley Rocha + two: - name: MyString - address: MyString - city: MyString - state: MyString - postal_code: MyString - phone: MyString + name: Curran Stout + + +three: + name: Roanna Robinson + + +four: + name: Carolyn Chandler + + +five: + name: Aquila Riddle + + +six: + name: Phyllis Russell + + +seven: + name: Rajah Riggs + + +eight: + name: Amanda Curtis + + +nine: + name: Jacqueline Perry + + +ten: + name: Quinlan Rich + + +eleven: + name: Ciara Summers + + +twelve: + name: Alfreda Hines + + +thirteen: + name: Eugenia Roberson From dfc3908ee1e9731ce39c87fb9e97448166771d98 Mon Sep 17 00:00:00 2001 From: kseastman Date: Wed, 9 May 2018 16:26:24 -0700 Subject: [PATCH 26/36] temporary unsatisfactory solution in customers_controller for params query. --- app/controllers/customers_controller.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index c5cfe7c6f..bd2373076 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -1,11 +1,15 @@ class CustomersController < ApplicationController def index - @customers = Customer.all + if params[:sort] + @customers = Customer.order(:name) + else + @customers = Customer.all + end if @customers.empty? render json: {errors: { customer: ["No customers were found"] } - }, status: :not_found + }, status: :not_found else render 'index.json' From 23f706e44c0e0d1ea5498324f8d588ca23a33e09 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Wed, 9 May 2018 17:27:16 -0700 Subject: [PATCH 27/36] optional params accounted for in customers controller. Controller tests passing --- app/controllers/customers_controller.rb | 65 ++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index bd2373076..15332150b 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -1,10 +1,71 @@ class CustomersController < ApplicationController def index - if params[:sort] - @customers = Customer.order(:name) + + queries = { + sort: params["sort"], + n: params["n"], + p: params["p"] + } + + + if queries[:sort] + @customers = Customer.all + @customers = @customers.order(queries[:sort]) + + if queries[:p] + if queries[:n] + # IF BOTH P AND N + start_index = ( queries[:p].to_i - 1 ) * queries[:n].to_i + ending_index = start_index + queries[:n].to_i + @customers = @customers[start_index...ending_index] + + else + # IF ONLY P + start_index = (queries[:p].to_i - 1) * 10 + ending_index = start_index + 10 + + @customers = @customers[start_index...ending_index] + + end + elsif queries[:n] + # IF ONLY N + start_index = 0 + ending_index = queries[:n].to_i + + @customers = @customers[start_index...ending_index] + + end + else + @customers = Customer.all + + if queries[:p] + if queries[:n] + # IF BOTH P AND N WITHOUT SORT + start_index = ( queries[:p].to_i - 1 ) * queries[:n].to_i + ending_index = start_index + queries[:n].to_i + @customers = @customers[start_index...ending_index] + + else + # IF ONLY P WITHOUT SORT + start_index = (queries[:p].to_i - 1) * 10 + ending_index = start_index + 10 + + @customers = @customers[start_index...ending_index] + + end + elsif queries[:n] + # IF ONLY N WITHOUT SORT + start_index = 0 + ending_index = queries[:n].to_i + + @customers = @customers[start_index...ending_index] + + end + end + if @customers.empty? render json: {errors: { customer: ["No customers were found"] From b43346c84b4e5ae48ef55da9b1c8e2084bf9952d Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Wed, 9 May 2018 17:47:18 -0700 Subject: [PATCH 28/36] Add tests for customer model request query method. Tests not passing yet --- app/models/customer.rb | 4 ++ test/models/customer_test.rb | 117 ++++++++++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 17 deletions(-) diff --git a/app/models/customer.rb b/app/models/customer.rb index aac1b8d04..388169df6 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -32,4 +32,8 @@ def checkedout return rented_count end + def self.request_query(params) + + end + end diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 9834b334e..3856edaa0 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -1,6 +1,36 @@ require "test_helper" describe Customer do + + describe "#checkedout" do + before do + @customer = Customer.first + @movie = Movie.first + end + + it "returns an integer of available inventory" do + result = @customer.checkedout + result.must_be_kind_of Integer + end + + it "updates when checkout and checkin" do + original_checkedout = @customer.checkedout + + rental = Rental.create_from_request(movie_id: @movie.id, customer_id: @customer.id) + rental.save + + result = @customer.checkedout + result.must_equal original_checkedout + 1 + + rental.checkin_date = DateTime.now + rental.save + + new_result = @customer.checkedout + new_result.must_equal original_checkedout + end + end + + describe "create from json" do it "can create a new instance from hash" do hash = { @@ -39,32 +69,85 @@ end end - describe "#checkedout" do - before do - @customer = Customer.first - @movie = Movie.first + describe "Customer.request_query" do + + it "takes in a hash and returns a collection of customers" do + params_hash = { + "sort": "name", + "p": "2", + "n": "5" + } + expected_length = 5 + sorted_cust = Customer.all.order_by(:name) + + result = Customer.request_query(params_hash) + result.must_be_kind_of Array + result.each do |customer| + customer.must_be_kind_of Customer + end + result.length.must_equal expected_length + names = result.map { |customer| customer.name } + names.sort.must_equal names + result.must_equal sorted_cust[5..9] end - it "returns an integer of available inventory" do - result = @customer.checkedout - result.must_be_kind_of Integer + it "works if params hash empty" do + params_hash = {} + + result = Customer.request_query(params_hash) + result.must_be_kind_of Array + result.each do |customer| + customer.must_be_kind_of Customer + end + result.length.must_equal Customer.count end - it "updates when checkout and checkin" do - original_checkedout = @customer.checkedout + it "work if only one optional" do + params_hash = { + "p": "2", + } - rental = Rental.create_from_request(movie_id: @movie.id, customer_id: @customer.id) - rental.save + result = Customer.request_query(params_hash) + result.must_be_kind_of Array + result.each do |customer| + customer.must_be_kind_of Customer + end + result.length.must_equal 3 + end - result = @customer.checkedout - result.must_equal original_checkedout + 1 + it "works if two optionals" do + params_hash = { + "p": "4", + "n": "3" + } - rental.checkin_date = DateTime.now - rental.save + result = Customer.request_query(params_hash) + result.must_be_kind_of Array + result.each do |customer| + customer.must_be_kind_of Customer + end + result.length.must_equal 3 + end - new_result = @customer.checkedout - new_result.must_equal original_checkedout + it "works if all random incorrect params" do + params_hash = { + "kitties": "something", + "banana": "5", + "n": "bananas" + } + + result = Customer.request_query(params_hash) + result.must_be_kind_of Array + result.each do |customer| + customer.must_be_kind_of Customer + end + result.length.must_equal Customer.count end + + + end + + end From bbe9f734e4279182c1e129b47b69671192f5b1e1 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Wed, 9 May 2018 22:17:24 -0700 Subject: [PATCH 29/36] Adding request_query method to customer model. All tests passing --- app/models/customer.rb | 18 +++++++++++++++++- test/models/customer_test.rb | 12 ++++++------ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/app/models/customer.rb b/app/models/customer.rb index 388169df6..590c7ea5e 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -33,7 +33,23 @@ def checkedout end def self.request_query(params) + a = params[:sort] + b = params[:p].to_i + c = params[:n].to_i + customers = Customer.all + customers = customers.order(a) if a + customers = customers.to_a - end + if b > 0 || c > 0 + b = 1 if b == 0 + c = 10 if c == 0 + + start = ( b - 1 ) * c + finish = start + c + customers = customers[start...finish] + end + + return customers + end end diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 3856edaa0..85294078f 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -78,10 +78,10 @@ "n": "5" } expected_length = 5 - sorted_cust = Customer.all.order_by(:name) + sorted_cust = Customer.all.order(:name) result = Customer.request_query(params_hash) - result.must_be_kind_of Array + # result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -95,7 +95,7 @@ params_hash = {} result = Customer.request_query(params_hash) - result.must_be_kind_of Array + # result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -108,7 +108,7 @@ } result = Customer.request_query(params_hash) - result.must_be_kind_of Array + # result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -122,7 +122,7 @@ } result = Customer.request_query(params_hash) - result.must_be_kind_of Array + # result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -137,7 +137,7 @@ } result = Customer.request_query(params_hash) - result.must_be_kind_of Array + # result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end From f97e3c14a51833934365878255bcc4cbd108ffbc Mon Sep 17 00:00:00 2001 From: kseastman Date: Thu, 10 May 2018 23:18:10 -0700 Subject: [PATCH 30/36] addded fixtures, modified customer model test for movie, all movie_test.rb passing. --- app/models/movie.rb | 22 +++++++++++ test/fixtures/movies.yml | 61 +++++++++++++++++++++++++++++++ test/models/movie_test.rb | 77 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+) diff --git a/app/models/movie.rb b/app/models/movie.rb index 2fcfaccad..bdd552113 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -17,4 +17,26 @@ def available avail = (self.inventory - rented) return avail end + + def self.request_query(params) + full_list = Movie.all + if !params.empty? + max_results_num = params["n"] ||= 10 + page_num = params["p"] ||= 1 + sort = params["sort"] ||= :id + + + start_index = max_results_num.to_i * (page_num.to_i - 1) + + if start_index > 0 + end_index = (start_index.to_i + max_results_num.to_i) - 1 + else + end_index = -1 + end + + full_list = full_list.order(sort.to_sym)[start_index..end_index] + end + return full_list + end + end diff --git a/test/fixtures/movies.yml b/test/fixtures/movies.yml index 9107042c5..377f97bd0 100644 --- a/test/fixtures/movies.yml +++ b/test/fixtures/movies.yml @@ -15,3 +15,64 @@ three: overview: But what if this strange woman is a con artist. Or what if everything told is completely true. How could an ordinary boy be relied upon in something this big. Time will tell. release_date: 2006-10-01 inventory: 10 + + +four: + title: Robots Of Eternity + overview: The laid-back life of a woman is going in a different direction as a childhood friend enters her life. + release_date: 2007-10-10 + inventory: 7 + +five: + title: Rats And Strangers + overview: The childhood friend claims the woman is heir to an incredible fortune, all paperwork has been taken care of already, all there's left to do is sign them. Distrustful of both this situation and of this childhood friend, the woman somewhat gladly agrees to the proposal, but there's no time to waste, a decision had to be made quickly. + release_date: 2012-09-25 + inventory: 2 + +six: + title: Soldiers And Gangsters + overview: But what if this childhood friend is just a crazy person. Or what if the complete opposite is true. How could an ordinary woman be relied upon in something this big. No turning back now though. + release_date: 1948-03-31 + inventory: 9 + +seven: + title: Body Of Utopia + overview: The peaceful life of a teenage girl is going the complete opposite way as a stranger enters her life. + release_date: 1967-10-25 + inventory: 2 + +eight: + title: Faith Of The Ancestors + overview: The stranger claims the teenage girl is now part of a murder investigation and might be the number one suspect, no arrest will be made in front of possible friends and neighbors if there's no resistance. Concerned of the situation and a little distrustful of this stranger, the teenage girl tentatively agrees to the proposal, no matter what, something has to be done in this situation, hopefully this was the right choice. + release_date: 1953-10-05 + inventory: 7 + +nine: + title: Traces In The Leaders + overview: But what if this stranger cannot be relied upon. Or what if somebody is orchestrating all of this. How could an ordinary teenage girl figure out the truth in all of this. Either way, the choice has been made. + release_date: 1970-11-03 + inventory: 6 + +ten: + title: Bathing In The Void + overview: The stressful life of a girl changes for better or worse as a stranger enters her life. + release_date: 2013-09-13 + inventory: 10 + +eleven: + title: Mouse Of My House + overview: The stranger claims the girl is now cursed along with everybody else in this town. Why? By whom? What kind of curse exactly? Nobody seems to know, but the person supposedly responsible for this curse will explain everything at the town hall this afternoon, everybody should come. Unsure what to think of all this and of this stranger, the girl cautiously agrees to the proposal, it all seemed rather odd, but there was no time to waste and a choice had to be made. + release_date: 1993-12-27 + inventory: 3 + +twelve: + title: Baby Of Tomorrow + overview: But what if this stranger is trying be misleading. Or what if the complete opposite is true. How could an ordinary girl find out what's happening without help. Only one way to find out. + release_date: 1977-03-23 + inventory: 4 + +thirteen: + title: Cats Of Wonder + overview: The carefree life of a young girl will change forever as a neighbor enters her life. + release_date: 1939-03-13 + inventory: 9 diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index e494cb134..9ddd71000 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -77,6 +77,83 @@ new_result = @movie.available new_result.must_equal original_avail end + end + + describe "Movie.request_query" do + + it "takes in a hash and returns a collection of movies" do + params_hash = { + "sort" => "title", + "p" => "2", + "n" => "5" + } + expected_length = 5 + sorted_movies = Movie.all.order(:title) + + result = Movie.request_query(params_hash) + result.must_be_kind_of Array + result.each do |movie| + movie.must_be_kind_of Movie + end + result.length.must_equal expected_length + names = result.map { |movie| movie.title } + names.sort.must_equal names + result.must_equal sorted_movies[5..9] + end + + it "works if params hash empty" do + params_hash = {} + + result = Movie.request_query(params_hash) + result.each do |movie| + movie.must_be_kind_of Movie + end + result.length.must_equal Movie.count + end + + it "work if only one optional" do + params_hash = { + "p" => "2", + } + + result = Movie.request_query(params_hash) + result.must_be_kind_of Array + result.each do |movie| + movie.must_be_kind_of Movie + end + result.length.must_equal 3 + end + + it "works if two optionals" do + params_hash = { + "p" => "4", + "n" => "3" + } + + result = Movie.request_query(params_hash) + result.must_be_kind_of Array + result.each do |movie| + movie.must_be_kind_of Movie + end + result.length.must_equal 3 + end + + it "works if all random incorrect params" do + params_hash = { + "kitties"=> "something", + "banana"=> "5", + "n"=> "bananas" + } + + result = Movie.request_query(params_hash) + result.must_be_kind_of Array + result.each do |movie| + movie.must_be_kind_of Movie + end + result.length.must_equal Movie.count + end + + end From 57a6eac53e8241e8441158b50a7fc1a7f86afc27 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Fri, 11 May 2018 10:57:07 -0700 Subject: [PATCH 31/36] refactoring. all tests passing --- test/models/customer_test.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 85294078f..95306d904 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -81,7 +81,7 @@ sorted_cust = Customer.all.order(:name) result = Customer.request_query(params_hash) - # result.must_be_kind_of Array + result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -95,7 +95,7 @@ params_hash = {} result = Customer.request_query(params_hash) - # result.must_be_kind_of Array + result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -108,7 +108,7 @@ } result = Customer.request_query(params_hash) - # result.must_be_kind_of Array + result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end @@ -122,7 +122,7 @@ } result = Customer.request_query(params_hash) - # result.must_be_kind_of Array + result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end From ebb5127ac20ea843ae4b4920eafa16fb30ec2c12 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Fri, 11 May 2018 13:37:30 -0700 Subject: [PATCH 32/36] moving customer model method to application record to be shared --- app/models/application_record.rb | 22 ++++++++++++++++++++++ app/models/customer.rb | 21 +-------------------- test/models/customer_test.rb | 13 +++++++------ 3 files changed, 30 insertions(+), 26 deletions(-) diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 10a4cba84..f68109fad 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,3 +1,25 @@ class ApplicationRecord < ActiveRecord::Base self.abstract_class = true + + def self.request_query(params, model) + a = params[:sort] + b = params[:p].to_i + c = params[:n].to_i + customers = model.all + acceptable = model.new.attributes.keys + customers = customers.order(a) if acceptable.include?(a) + customers = customers.to_a + + if b > 0 || c > 0 + b = 1 if b == 0 + c = 10 if c == 0 + + start = ( b - 1 ) * c + finish = start + c + + customers = customers[start...finish] + end + + return customers + end end diff --git a/app/models/customer.rb b/app/models/customer.rb index 590c7ea5e..53897c12e 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -32,24 +32,5 @@ def checkedout return rented_count end - def self.request_query(params) - a = params[:sort] - b = params[:p].to_i - c = params[:n].to_i - customers = Customer.all - customers = customers.order(a) if a - customers = customers.to_a - - if b > 0 || c > 0 - b = 1 if b == 0 - c = 10 if c == 0 - - start = ( b - 1 ) * c - finish = start + c - - customers = customers[start...finish] - end - - return customers - end + end diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index 95306d904..78330a476 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -80,7 +80,7 @@ expected_length = 5 sorted_cust = Customer.all.order(:name) - result = Customer.request_query(params_hash) + result = Customer.request_query(params_hash, Customer) result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer @@ -94,7 +94,7 @@ it "works if params hash empty" do params_hash = {} - result = Customer.request_query(params_hash) + result = Customer.request_query(params_hash, Customer) result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer @@ -107,7 +107,7 @@ "p": "2", } - result = Customer.request_query(params_hash) + result = Customer.request_query(params_hash, Customer) result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer @@ -121,7 +121,7 @@ "n": "3" } - result = Customer.request_query(params_hash) + result = Customer.request_query(params_hash, Customer) result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer @@ -131,13 +131,14 @@ it "works if all random incorrect params" do params_hash = { + "sort": "somethingelse", "kitties": "something", "banana": "5", "n": "bananas" } - result = Customer.request_query(params_hash) - # result.must_be_kind_of Array + result = Customer.request_query(params_hash, Customer) + result.must_be_kind_of Array result.each do |customer| customer.must_be_kind_of Customer end From d742286d37ab9a5be33b661f67b271c635aa6efc Mon Sep 17 00:00:00 2001 From: kseastman Date: Fri, 11 May 2018 13:38:34 -0700 Subject: [PATCH 33/36] movie version deprecated --- app/controllers/movies_controller.rb | 2 +- app/models/movie.rb | 6 +++--- test/models/movie_test.rb | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index fc79d76c8..14745a9fe 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -5,7 +5,7 @@ def zomg end def index - @movies = Movie.all + @movies = Movie.request_query(params) if @movies.empty? render json: { diff --git a/app/models/movie.rb b/app/models/movie.rb index bdd552113..bb4b5e419 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -21,8 +21,8 @@ def available def self.request_query(params) full_list = Movie.all if !params.empty? - max_results_num = params["n"] ||= 10 - page_num = params["p"] ||= 1 + max_results_num = params["n"].to_i ||= 10 + page_num = params["p"].to_i ||= 1 sort = params["sort"] ||= :id @@ -34,7 +34,7 @@ def self.request_query(params) end_index = -1 end - full_list = full_list.order(sort.to_sym)[start_index..end_index] + full_list = full_list.order(sort)[start_index..end_index] end return full_list end diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index 9ddd71000..b304b4af6 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -105,6 +105,7 @@ params_hash = {} result = Movie.request_query(params_hash) + result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie end From a673a136aa22c12d427600353ed670cbdb7fec28 Mon Sep 17 00:00:00 2001 From: kseastman Date: Fri, 11 May 2018 13:46:27 -0700 Subject: [PATCH 34/36] request_query optionals passing tests and implemented for movies. --- app/controllers/movies_controller.rb | 2 +- app/models/movie.rb | 21 ---------------- test/models/movie_test.rb | 36 ++++++++++++++-------------- 3 files changed, 19 insertions(+), 40 deletions(-) diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index 14745a9fe..5fe475e7e 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -5,7 +5,7 @@ def zomg end def index - @movies = Movie.request_query(params) + @movies = Movie.request_query(params, Movie) if @movies.empty? render json: { diff --git a/app/models/movie.rb b/app/models/movie.rb index bb4b5e419..61221f96b 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -18,25 +18,4 @@ def available return avail end - def self.request_query(params) - full_list = Movie.all - if !params.empty? - max_results_num = params["n"].to_i ||= 10 - page_num = params["p"].to_i ||= 1 - sort = params["sort"] ||= :id - - - start_index = max_results_num.to_i * (page_num.to_i - 1) - - if start_index > 0 - end_index = (start_index.to_i + max_results_num.to_i) - 1 - else - end_index = -1 - end - - full_list = full_list.order(sort)[start_index..end_index] - end - return full_list - end - end diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index b304b4af6..3d07975b1 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -21,9 +21,9 @@ it "doesn't create an instance with incomplete data" do hash = { - "overview" => "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", - "release_date" => "1979-01-18", - "inventory" => 10 + "overview": "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", + "release_date": "1979-01-18", + "inventory": 10 } old_count = Movie.count @@ -36,10 +36,10 @@ it "doesn't create an instance with unacceptable data" do hash = { - "title" => "Some Title", - "overview" => "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", - "release_date" => "1979-01-18", - "inventory" => -7 + "title": "Some Title", + "overview": "The unexciting life of a boy will be permanently altered as a strange woman enters his life.", + "release_date": "1979-01-18", + "inventory": -7 } old_count = Movie.count @@ -83,14 +83,14 @@ it "takes in a hash and returns a collection of movies" do params_hash = { - "sort" => "title", - "p" => "2", - "n" => "5" + "sort": "title", + "p": "2", + "n": "5" } expected_length = 5 sorted_movies = Movie.all.order(:title) - result = Movie.request_query(params_hash) + result = Movie.request_query(params_hash, Movie) result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie @@ -104,7 +104,7 @@ it "works if params hash empty" do params_hash = {} - result = Movie.request_query(params_hash) + result = Movie.request_query(params_hash, Movie) result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie @@ -114,10 +114,10 @@ it "work if only one optional" do params_hash = { - "p" => "2", + "p": "2", } - result = Movie.request_query(params_hash) + result = Movie.request_query(params_hash, Movie) result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie @@ -127,11 +127,11 @@ it "works if two optionals" do params_hash = { - "p" => "4", - "n" => "3" + "p": "4", + "n": "3" } - result = Movie.request_query(params_hash) + result = Movie.request_query(params_hash, Movie) result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie @@ -146,7 +146,7 @@ "n"=> "bananas" } - result = Movie.request_query(params_hash) + result = Movie.request_query(params_hash, Movie) result.must_be_kind_of Array result.each do |movie| movie.must_be_kind_of Movie From b0ca22bc3ec575a8e99f7028b060ec61ea185d2d Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Fri, 11 May 2018 13:49:10 -0700 Subject: [PATCH 35/36] Final refactoring of customer --- app/controllers/customers_controller.rb | 66 +------------------------ 1 file changed, 1 insertion(+), 65 deletions(-) diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 15332150b..3814beb46 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -1,70 +1,6 @@ class CustomersController < ApplicationController def index - - queries = { - sort: params["sort"], - n: params["n"], - p: params["p"] - } - - - if queries[:sort] - @customers = Customer.all - @customers = @customers.order(queries[:sort]) - - if queries[:p] - if queries[:n] - # IF BOTH P AND N - start_index = ( queries[:p].to_i - 1 ) * queries[:n].to_i - ending_index = start_index + queries[:n].to_i - @customers = @customers[start_index...ending_index] - - else - # IF ONLY P - start_index = (queries[:p].to_i - 1) * 10 - ending_index = start_index + 10 - - @customers = @customers[start_index...ending_index] - - end - elsif queries[:n] - # IF ONLY N - start_index = 0 - ending_index = queries[:n].to_i - - @customers = @customers[start_index...ending_index] - - end - - else - - @customers = Customer.all - - if queries[:p] - if queries[:n] - # IF BOTH P AND N WITHOUT SORT - start_index = ( queries[:p].to_i - 1 ) * queries[:n].to_i - ending_index = start_index + queries[:n].to_i - @customers = @customers[start_index...ending_index] - - else - # IF ONLY P WITHOUT SORT - start_index = (queries[:p].to_i - 1) * 10 - ending_index = start_index + 10 - - @customers = @customers[start_index...ending_index] - - end - elsif queries[:n] - # IF ONLY N WITHOUT SORT - start_index = 0 - ending_index = queries[:n].to_i - - @customers = @customers[start_index...ending_index] - - end - - end + @customers = Customer.request_query(params, Customer) if @customers.empty? render json: {errors: { From 450e87a80e3b50a203ea6e4b91a036afdd384f29 Mon Sep 17 00:00:00 2001 From: Karinna Iniguez Date: Fri, 11 May 2018 14:00:31 -0700 Subject: [PATCH 36/36] Add invalid sort to movie model testing --- test/models/movie_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/test/models/movie_test.rb b/test/models/movie_test.rb index 3d07975b1..a731fac4d 100644 --- a/test/models/movie_test.rb +++ b/test/models/movie_test.rb @@ -141,6 +141,7 @@ it "works if all random incorrect params" do params_hash = { + "sort": "somethingelse", "kitties"=> "something", "banana"=> "5", "n"=> "bananas"