From 887b42325102a9282459c1adbd9a269b1aa471e7 Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Sat, 4 May 2019 19:55:05 +0300 Subject: [PATCH 1/8] Add spec for rake task --- .rspec | 1 + Gemfile | 1 + Gemfile.lock | 19 ++++++ spec/rails_helper.rb | 61 ++++++++++++++++++ spec/rake_tasks/utils_spec.rb | 18 ++++++ spec/spec_helper.rb | 96 ++++++++++++++++++++++++++++ test/application_system_test_case.rb | 5 -- test/controllers/.keep | 0 test/fixtures/.keep | 0 test/fixtures/files/.keep | 0 test/helpers/.keep | 0 test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/system/.keep | 0 test/test_helper.rb | 10 --- 16 files changed, 196 insertions(+), 15 deletions(-) create mode 100644 .rspec create mode 100644 spec/rails_helper.rb create mode 100644 spec/rake_tasks/utils_spec.rb create mode 100644 spec/spec_helper.rb delete mode 100644 test/application_system_test_case.rb delete mode 100644 test/controllers/.keep delete mode 100644 test/fixtures/.keep delete mode 100644 test/fixtures/files/.keep delete mode 100644 test/helpers/.keep delete mode 100644 test/integration/.keep delete mode 100644 test/mailers/.keep delete mode 100644 test/models/.keep delete mode 100644 test/system/.keep delete mode 100644 test/test_helper.rb diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..c99d2e7 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/Gemfile b/Gemfile index 33017fd..1534826 100644 --- a/Gemfile +++ b/Gemfile @@ -11,6 +11,7 @@ gem 'bootsnap', '>= 1.1.0', require: false 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] + gem 'rspec-rails', '~> 3.8' end group :development do diff --git a/Gemfile.lock b/Gemfile.lock index eb22e16..b24b09d 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -50,6 +50,7 @@ GEM byebug (11.0.1) concurrent-ruby (1.1.5) crass (1.0.4) + diff-lcs (1.3) erubi (1.8.0) ffi (1.10.0) globalid (0.4.2) @@ -109,6 +110,23 @@ GEM rb-fsevent (0.10.3) rb-inotify (0.10.0) ffi (~> 1.0) + rspec-core (3.8.0) + rspec-support (~> 3.8.0) + rspec-expectations (3.8.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.8.0) + rspec-mocks (3.8.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.8.0) + rspec-rails (3.8.2) + actionpack (>= 3.0) + activesupport (>= 3.0) + railties (>= 3.0) + rspec-core (~> 3.8.0) + rspec-expectations (~> 3.8.0) + rspec-mocks (~> 3.8.0) + rspec-support (~> 3.8.0) + rspec-support (3.8.0) ruby_dep (1.5.0) sprockets (3.7.2) concurrent-ruby (~> 1.0) @@ -140,6 +158,7 @@ DEPENDENCIES pg (>= 0.18, < 2.0) puma (~> 3.11) rails (~> 5.2.3) + rspec-rails (~> 3.8) tzinfo-data web-console (>= 3.3.0) diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..d73d80b --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,61 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + puts e.to_s.strip + exit 1 +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, :type => :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/spec/rake_tasks/utils_spec.rb b/spec/rake_tasks/utils_spec.rb new file mode 100644 index 0000000..4d3e65d --- /dev/null +++ b/spec/rake_tasks/utils_spec.rb @@ -0,0 +1,18 @@ +require 'rails_helper' +require 'rake' + +describe 'stats:fix_all'do + before do + Rake.application.rake_require 'tasks/utils' + Rake::Task.define_task(:environment) + end + + subject(:task) { Rake::Task["reload_json"].invoke('fixtures/example.json') } + + it 'creates data' do + expect { task }.to change(Bus, :count).by(1) + .and(change(Trip, :count).by(10)) + .and(change(City, :count).by(2)) + .and(change(Service, :count).by(2)) + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..ce33d66 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,96 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb deleted file mode 100644 index d19212a..0000000 --- a/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :chrome, screen_size: [1400, 1400] -end diff --git a/test/controllers/.keep b/test/controllers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/fixtures/.keep b/test/fixtures/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/helpers/.keep b/test/helpers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/integration/.keep b/test/integration/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/mailers/.keep b/test/mailers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/models/.keep b/test/models/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/system/.keep b/test/system/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/test_helper.rb b/test/test_helper.rb deleted file mode 100644 index 3ab84e3..0000000 --- a/test/test_helper.rb +++ /dev/null @@ -1,10 +0,0 @@ -ENV['RAILS_ENV'] ||= 'test' -require_relative '../config/environment' -require 'rails/test_help' - -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 From a734b8d44cb3d55ad4db9be6e5164fc9e5fc3d0a Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Sun, 5 May 2019 11:22:44 +0300 Subject: [PATCH 2/8] feat(Bus): Add uniq index on number & Remove uniqueness validation --- Gemfile | 1 + Gemfile.lock | 8 ++++++++ app/models/bus.rb | 2 +- .../20190505081329_add_uniq_index_to_buses.rb | 5 +++++ db/schema.rb | 3 ++- spec/models/bus_spec.rb | 20 +++++++++++++++++++ spec/rails_helper.rb | 1 + 7 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20190505081329_add_uniq_index_to_buses.rb create mode 100644 spec/models/bus_spec.rb diff --git a/Gemfile b/Gemfile index 1534826..62d9c2b 100644 --- a/Gemfile +++ b/Gemfile @@ -21,6 +21,7 @@ group :development do end group :test do + gem 'rspec-sqlimit' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem diff --git a/Gemfile.lock b/Gemfile.lock index b24b09d..bd9f129 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -110,6 +110,10 @@ GEM rb-fsevent (0.10.3) rb-inotify (0.10.0) ffi (~> 1.0) + rspec (3.8.0) + rspec-core (~> 3.8.0) + rspec-expectations (~> 3.8.0) + rspec-mocks (~> 3.8.0) rspec-core (3.8.0) rspec-support (~> 3.8.0) rspec-expectations (3.8.3) @@ -126,6 +130,9 @@ GEM rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-support (~> 3.8.0) + rspec-sqlimit (0.0.2) + rails (> 4.0, < 6.0) + rspec (~> 3.0) rspec-support (3.8.0) ruby_dep (1.5.0) sprockets (3.7.2) @@ -159,6 +166,7 @@ DEPENDENCIES puma (~> 3.11) rails (~> 5.2.3) rspec-rails (~> 3.8) + rspec-sqlimit tzinfo-data web-console (>= 3.3.0) diff --git a/app/models/bus.rb b/app/models/bus.rb index 1dcc54c..3ccce29 100644 --- a/app/models/bus.rb +++ b/app/models/bus.rb @@ -15,6 +15,6 @@ class Bus < ApplicationRecord has_many :trips has_and_belongs_to_many :services, join_table: :buses_services - validates :number, presence: true, uniqueness: true + validates :number, presence: true validates :model, inclusion: { in: MODELS } end diff --git a/db/migrate/20190505081329_add_uniq_index_to_buses.rb b/db/migrate/20190505081329_add_uniq_index_to_buses.rb new file mode 100644 index 0000000..34419ea --- /dev/null +++ b/db/migrate/20190505081329_add_uniq_index_to_buses.rb @@ -0,0 +1,5 @@ +class AddUniqIndexToBuses < ActiveRecord::Migration[5.2] + def change + add_index :buses, :number, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index f6921e4..8b8ae05 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_03_30_193044) do +ActiveRecord::Schema.define(version: 2019_05_05_081329) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -18,6 +18,7 @@ create_table "buses", force: :cascade do |t| t.string "number" t.string "model" + t.index ["number"], name: "index_buses_on_number", unique: true end create_table "buses_services", force: :cascade do |t| diff --git a/spec/models/bus_spec.rb b/spec/models/bus_spec.rb new file mode 100644 index 0000000..ec521cc --- /dev/null +++ b/spec/models/bus_spec.rb @@ -0,0 +1,20 @@ +require 'rails_helper' + +describe Bus do + describe '.create' do + subject(:create) do + Bus.create(model: Bus::MODELS.first, number: 1) + rescue + nil + end + + it "doesn't sends request to check uniqueness of name" do + expect { create }.not_to exceed_query_limit(0).with(/^SELECT/) + end + + it "doesn't create bus with existed number" do + Bus.create(model: Bus::MODELS.last, number: 1) + expect { create }.not_to change(Bus, :count) + end + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index d73d80b..80a1c8f 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -5,6 +5,7 @@ # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' +require "rspec-sqlimit" # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in From ea598b8efbb596e24a148a9ba507171a0f440044 Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Sun, 5 May 2019 11:32:22 +0300 Subject: [PATCH 3/8] feat(City): Add uniq index on name & Remove uniqueness validation --- app/models/city.rb | 2 +- ...20190505083024_add_uniq_index_to_cities.rb | 5 +++++ db/schema.rb | 3 ++- spec/models/city_spec.rb | 20 +++++++++++++++++++ 4 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20190505083024_add_uniq_index_to_cities.rb create mode 100644 spec/models/city_spec.rb diff --git a/app/models/city.rb b/app/models/city.rb index 19ec7f3..b5528fb 100644 --- a/app/models/city.rb +++ b/app/models/city.rb @@ -1,5 +1,5 @@ class City < ApplicationRecord - validates :name, presence: true, uniqueness: true + validates :name, presence: true validate :name_has_no_spaces def name_has_no_spaces diff --git a/db/migrate/20190505083024_add_uniq_index_to_cities.rb b/db/migrate/20190505083024_add_uniq_index_to_cities.rb new file mode 100644 index 0000000..c28495d --- /dev/null +++ b/db/migrate/20190505083024_add_uniq_index_to_cities.rb @@ -0,0 +1,5 @@ +class AddUniqIndexToCities < ActiveRecord::Migration[5.2] + def change + add_index :cities, :name, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 8b8ae05..4037f13 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_05_05_081329) do +ActiveRecord::Schema.define(version: 2019_05_05_083024) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -28,6 +28,7 @@ create_table "cities", force: :cascade do |t| t.string "name" + t.index ["name"], name: "index_cities_on_name", unique: true end create_table "services", force: :cascade do |t| diff --git a/spec/models/city_spec.rb b/spec/models/city_spec.rb new file mode 100644 index 0000000..cd46995 --- /dev/null +++ b/spec/models/city_spec.rb @@ -0,0 +1,20 @@ +require 'rails_helper' + +describe City do + describe '.create' do + subject(:create) do + City.create(name: 'Bolhov') + rescue + nil + end + + it "doesn't sends request to check uniqueness of name" do + expect { create }.not_to exceed_query_limit(0).with(/^SELECT/) + end + + it "doesn't create bus with existed name" do + City.create(name: 'Bolhov') + expect { create }.not_to change(City, :count) + end + end +end From 63826c579bb3039ef43b1a44c261ffdbcfe7d125 Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Sun, 5 May 2019 11:38:53 +0300 Subject: [PATCH 4/8] feat(Service): Add uniq index on name --- db/migrate/20190505083758_add_uniq_index_to_services.rb | 5 +++++ db/schema.rb | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20190505083758_add_uniq_index_to_services.rb diff --git a/db/migrate/20190505083758_add_uniq_index_to_services.rb b/db/migrate/20190505083758_add_uniq_index_to_services.rb new file mode 100644 index 0000000..b2bd233 --- /dev/null +++ b/db/migrate/20190505083758_add_uniq_index_to_services.rb @@ -0,0 +1,5 @@ +class AddUniqIndexToServices < ActiveRecord::Migration[5.2] + def change + add_index :services, :name, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 4037f13..8f9a793 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_05_05_083024) do +ActiveRecord::Schema.define(version: 2019_05_05_083758) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -33,6 +33,7 @@ create_table "services", force: :cascade do |t| t.string "name" + t.index ["name"], name: "index_services_on_name", unique: true end create_table "trips", force: :cascade do |t| From 6999f84febe21137f7be6a13292e58ed7a3a306a Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Mon, 6 May 2019 16:17:18 +0300 Subject: [PATCH 5/8] refact rake task [3min] --- Gemfile | 2 + Gemfile.lock | 8 +++ lib/tasks/utils.rake | 111 +++++++++++++++++++++++++++------- spec/rake_tasks/utils_spec.rb | 2 +- 4 files changed, 101 insertions(+), 22 deletions(-) diff --git a/Gemfile b/Gemfile index 62d9c2b..8ea27b4 100644 --- a/Gemfile +++ b/Gemfile @@ -7,11 +7,13 @@ gem 'rails', '~> 5.2.3' gem 'pg', '>= 0.18', '< 2.0' gem 'puma', '~> 3.11' gem 'bootsnap', '>= 1.1.0', require: false +gem 'activerecord-import' 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] gem 'rspec-rails', '~> 3.8' + gem 'pry' end group :development do diff --git a/Gemfile.lock b/Gemfile.lock index bd9f129..e038387 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -33,6 +33,8 @@ GEM activemodel (= 5.2.3) activesupport (= 5.2.3) arel (>= 9.0) + activerecord-import (1.0.1) + activerecord (>= 3.2) activestorage (5.2.3) actionpack (= 5.2.3) activerecord (= 5.2.3) @@ -48,6 +50,7 @@ GEM msgpack (~> 1.0) builder (3.2.3) byebug (11.0.1) + coderay (1.1.2) concurrent-ruby (1.1.5) crass (1.0.4) diff-lcs (1.3) @@ -78,6 +81,9 @@ GEM nokogiri (1.10.2) mini_portile2 (~> 2.4.0) pg (1.1.4) + pry (0.12.2) + coderay (~> 1.1.0) + method_source (~> 0.9.0) puma (3.12.1) rack (2.0.6) rack-test (1.1.0) @@ -159,10 +165,12 @@ PLATFORMS ruby DEPENDENCIES + activerecord-import bootsnap (>= 1.1.0) byebug listen (>= 3.0.5, < 3.2) pg (>= 0.18, < 2.0) + pry puma (~> 3.11) rails (~> 5.2.3) rspec-rails (~> 3.8) diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake index 540fe87..ce90f4a 100644 --- a/lib/tasks/utils.rake +++ b/lib/tasks/utils.rake @@ -4,31 +4,100 @@ task :reload_json, [:file_name] => :environment do |_task, args| json = JSON.parse(File.read(args.file_name)) ActiveRecord::Base.transaction do - City.delete_all - Bus.delete_all - Service.delete_all - Trip.delete_all - ActiveRecord::Base.connection.execute('delete from buses_services;') - - json.each do |trip| - from = City.find_or_create_by(name: trip['from']) - to = City.find_or_create_by(name: trip['to']) - services = [] - trip['bus']['services'].each do |service| - s = Service.find_or_create_by(name: service) - services << s + migration = ActiveRecord::Migration + + # truncate tables + migration.execute(<<-SQL) + TRUNCATE cities, buses, services, trips, buses_services RESTART IDENTITY; + SQL + + # drop primary keys and indicies + migration.execute(<<-SQL.squish) + ALTER TABLE cities DROP CONSTRAINT cities_pkey; + ALTER TABLE buses DROP CONSTRAINT buses_pkey; + ALTER TABLE services DROP CONSTRAINT services_pkey; + ALTER TABLE trips DROP CONSTRAINT trips_pkey; + ALTER TABLE buses_services DROP CONSTRAINT buses_services_pkey; + DROP INDEX index_cities_on_name; + DROP INDEX index_buses_on_number; + DROP INDEX index_services_on_name + SQL + + # create services; add primary key and index; load + services = Service::SERVICES.map { |name| { name: name } } + Service.import(services) + migration.execute('ALTER TABLE services ADD PRIMARY KEY (id);') + migration.add_index(:services, :name, unique: true) + services = Service.pluck(:name, :id).to_h + + # create values to insert + #values = json.reduce({ cities: [], buses: [], buses_services: [], trips: [] }) do |h, obj| + # h[:cities] += [{ name: obj['from'] }, { name: obj['to'] }] + # h[:buses] << { model: obj.dig('bus', 'model'), number: obj.dig('bus', 'number') } + # h[:buses_services] += obj.dig('bus', 'services').map do |serv_name| + # { bus_id: obj.dig('bus', 'number'), service_id: services[serv_name] } + # end + # h[:trips] << { from_id: obj['from'], + # to_id: obj['to'], + # bus_id: obj.dig('bus', 'number'), + # start_time: obj['start_time'], + # duration_minutes: obj['duration_minutes'], + # price_cents: obj['price_cents'] } + # h + #end + + # create cities; add primary key and index; load + cities = json.reduce([]) { |arr, obj| arr += [obj['from'], obj['to']] }.uniq + cities = cities.map { |name| { name: name } } + City.import(cities) + #City.import(values[:cities].uniq) + migration.execute('ALTER TABLE cities ADD PRIMARY KEY (id);') + migration.add_index(:cities, :name, unique: true) + cities = City.pluck(:name, :id).to_h + + # create buses; add primary key and index; load + buses = json.map do |obj| + { model: obj.dig('bus', 'model'), number: obj.dig('bus', 'number') } + end.uniq + Bus.import(buses) + #Bus.import(values[:buses].uniq) + migration.execute('ALTER TABLE buses ADD PRIMARY KEY (id);') + migration.add_index(:buses, :number, unique: true) + buses = Bus.pluck(:number, :id).to_h + + # create buses_services; add primary key + BusesService = Class.new(ActiveRecord::Base) + BusesService.table_name = 'buses_services' + buses_services = json.reduce([]) do |arr, obj| + arr += obj.dig('bus', 'services').map do |serv_name| + { bus_id: buses[obj.dig('bus', 'number')], + service_id: services[serv_name] } end - bus = Bus.find_or_create_by(number: trip['bus']['number']) - bus.update(model: trip['bus']['model'], services: services) + end + #buses_services = values[:buses_services].uniq.map do |h| + # h[:bus_id] = buses[h[:bus_id]] + # h + #end + BusesService.import(buses_services) + Object.send(:remove_const, :BusesService) + migration.execute('ALTER TABLE buses_services ADD PRIMARY KEY (id);') - Trip.create!( - from: from, - to: to, - bus: bus, + # create trips; add primary key + trips = json.map do |trip| + { from_id: cities[trip['from']], + to_id: cities[trip['to']], + bus_id: buses[trip.dig('bus', 'number')], start_time: trip['start_time'], duration_minutes: trip['duration_minutes'], - price_cents: trip['price_cents'], - ) + price_cents: trip['price_cents'] } end + #trips = values[:trips].uniq.map do |h| + # h[:from_id] = cities[h[:from_id]] + # h[:to_id] = cities[h[:to_id]] + # h[:bus_id] = buses[h[:bus_id]] + # h + #end + Trip.import(trips) + migration.execute('ALTER TABLE trips ADD PRIMARY KEY (id);') end end diff --git a/spec/rake_tasks/utils_spec.rb b/spec/rake_tasks/utils_spec.rb index 4d3e65d..0d57018 100644 --- a/spec/rake_tasks/utils_spec.rb +++ b/spec/rake_tasks/utils_spec.rb @@ -13,6 +13,6 @@ expect { task }.to change(Bus, :count).by(1) .and(change(Trip, :count).by(10)) .and(change(City, :count).by(2)) - .and(change(Service, :count).by(2)) + .and(change(Service, :count).by(Service::SERVICES.size)) end end From 9287a08706335665e54e7ffa2071757c33122273 Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Wed, 8 May 2019 22:32:15 +0300 Subject: [PATCH 6/8] Refact rake task with jsonb [15 sec] --- lib/tasks/utils.rake | 96 ++++++++++++++--------------------- spec/rake_tasks/utils_spec.rb | 1 + 2 files changed, 39 insertions(+), 58 deletions(-) diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake index ce90f4a..38c6c4f 100644 --- a/lib/tasks/utils.rake +++ b/lib/tasks/utils.rake @@ -23,81 +23,61 @@ task :reload_json, [:file_name] => :environment do |_task, args| DROP INDEX index_services_on_name SQL - # create services; add primary key and index; load + # add temp columns to trips and import data + migration.add_column(:trips, :bus, :jsonb) + migration.add_column(:trips, :from, :varchar) + migration.add_column(:trips, :to, :varchar) + Trip.reset_column_information + Trip.import(json, validate: false, no_returning: true) + + # create services; add primary key and index services = Service::SERVICES.map { |name| { name: name } } Service.import(services) migration.execute('ALTER TABLE services ADD PRIMARY KEY (id);') + Service.primary_key = :id migration.add_index(:services, :name, unique: true) - services = Service.pluck(:name, :id).to_h - - # create values to insert - #values = json.reduce({ cities: [], buses: [], buses_services: [], trips: [] }) do |h, obj| - # h[:cities] += [{ name: obj['from'] }, { name: obj['to'] }] - # h[:buses] << { model: obj.dig('bus', 'model'), number: obj.dig('bus', 'number') } - # h[:buses_services] += obj.dig('bus', 'services').map do |serv_name| - # { bus_id: obj.dig('bus', 'number'), service_id: services[serv_name] } - # end - # h[:trips] << { from_id: obj['from'], - # to_id: obj['to'], - # bus_id: obj.dig('bus', 'number'), - # start_time: obj['start_time'], - # duration_minutes: obj['duration_minutes'], - # price_cents: obj['price_cents'] } - # h - #end - # create cities; add primary key and index; load - cities = json.reduce([]) { |arr, obj| arr += [obj['from'], obj['to']] }.uniq - cities = cities.map { |name| { name: name } } - City.import(cities) - #City.import(values[:cities].uniq) + # create cities; add primary key and index + cities = (Trip.distinct.pluck(:from) | Trip.distinct.pluck(:to)).map(&Array.method(:wrap)) + City.import([:name], cities) + City.primary_key = :id migration.execute('ALTER TABLE cities ADD PRIMARY KEY (id);') migration.add_index(:cities, :name, unique: true) - cities = City.pluck(:name, :id).to_h - # create buses; add primary key and index; load - buses = json.map do |obj| - { model: obj.dig('bus', 'model'), number: obj.dig('bus', 'number') } - end.uniq + # create buses; add primary key and index + buses = Trip.select("DISTINCT data") + .from("(SELECT (bus - 'services') AS data FROM trips) AS subquery") + .map(&:data) Bus.import(buses) - #Bus.import(values[:buses].uniq) migration.execute('ALTER TABLE buses ADD PRIMARY KEY (id);') + Bus.primary_key = :id migration.add_index(:buses, :number, unique: true) - buses = Bus.pluck(:number, :id).to_h # create buses_services; add primary key BusesService = Class.new(ActiveRecord::Base) - BusesService.table_name = 'buses_services' - buses_services = json.reduce([]) do |arr, obj| - arr += obj.dig('bus', 'services').map do |serv_name| - { bus_id: buses[obj.dig('bus', 'number')], - service_id: services[serv_name] } - end - end - #buses_services = values[:buses_services].uniq.map do |h| - # h[:bus_id] = buses[h[:bus_id]] - # h - #end - BusesService.import(buses_services) + buses_services = + Trip.unscoped + .joins("join buses on trips.bus->>'number' = buses.number") + .joins("join services on services.name = + ANY(select jsonb_array_elements_text((trips.bus->>'services')::jsonb))") + .group('buses.id, services.id') + .pluck('buses.id, services.id') + BusesService.import([:bus_id, :service_id], buses_services) Object.send(:remove_const, :BusesService) migration.execute('ALTER TABLE buses_services ADD PRIMARY KEY (id);') - # create trips; add primary key - trips = json.map do |trip| - { from_id: cities[trip['from']], - to_id: cities[trip['to']], - bus_id: buses[trip.dig('bus', 'number')], - start_time: trip['start_time'], - duration_minutes: trip['duration_minutes'], - price_cents: trip['price_cents'] } - end - #trips = values[:trips].uniq.map do |h| - # h[:from_id] = cities[h[:from_id]] - # h[:to_id] = cities[h[:to_id]] - # h[:bus_id] = buses[h[:bus_id]] - # h - #end - Trip.import(trips) + # update trips; remove temp columns; add primary key + Trip.where("trips.bus->>'model' = buses.model") + .where("trips.bus->>'number' = buses.number") + .update_all('bus_id = buses.id FROM buses') + Trip.where("trips.from = services.name") + .update_all('from_id = services.id FROM services') + Trip.where("trips.to = services.name") + .update_all('to_id = services.id FROM services') + migration.remove_column(:trips, :bus) + migration.remove_column(:trips, :from) + migration.remove_column(:trips, :to) migration.execute('ALTER TABLE trips ADD PRIMARY KEY (id);') + Trip.primary_key = :id end end diff --git a/spec/rake_tasks/utils_spec.rb b/spec/rake_tasks/utils_spec.rb index 0d57018..b8114b8 100644 --- a/spec/rake_tasks/utils_spec.rb +++ b/spec/rake_tasks/utils_spec.rb @@ -14,5 +14,6 @@ .and(change(Trip, :count).by(10)) .and(change(City, :count).by(2)) .and(change(Service, :count).by(Service::SERVICES.size)) + .and(change { Bus.last&.services&.count }.from(nil).to(2)) end end From 71e908fb38a95b6bce30572de969d7ee0ffa557d Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Tue, 14 May 2019 08:46:30 +0300 Subject: [PATCH 7/8] Add more indicies --- Gemfile | 3 +++ Gemfile.lock | 7 +++++++ app/controllers/trips_controller.rb | 5 ++++- app/models/trip.rb | 11 +++++++++++ app/views/trips/_services.html.erb | 6 ------ app/views/trips/_trip.html.erb | 18 +++++++++++++----- app/views/trips/index.html.erb | 12 ++---------- ...0190509064555_add_from_to_index_to_trips.rb | 5 +++++ ...70919_add_bus_id_index_to_buses_services.rb | 5 +++++ db/schema.rb | 4 +++- lib/tasks/utils.rake | 14 +++++++++----- spec/rails_helper.rb | 2 ++ 12 files changed, 64 insertions(+), 28 deletions(-) delete mode 100644 app/views/trips/_services.html.erb create mode 100644 db/migrate/20190509064555_add_from_to_index_to_trips.rb create mode 100644 db/migrate/20190509070919_add_bus_id_index_to_buses_services.rb diff --git a/Gemfile b/Gemfile index 8ea27b4..b85d8dc 100644 --- a/Gemfile +++ b/Gemfile @@ -8,6 +8,7 @@ gem 'pg', '>= 0.18', '< 2.0' gem 'puma', '~> 3.11' gem 'bootsnap', '>= 1.1.0', require: false gem 'activerecord-import' +gem "rack-mini-profiler" group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console @@ -20,6 +21,8 @@ group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' + gem 'stackprof' + gem "flamegraph" end group :test do diff --git a/Gemfile.lock b/Gemfile.lock index e038387..d0aae89 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -56,6 +56,7 @@ GEM diff-lcs (1.3) erubi (1.8.0) ffi (1.10.0) + flamegraph (0.9.5) globalid (0.4.2) activesupport (>= 4.2.0) i18n (1.6.0) @@ -86,6 +87,8 @@ GEM method_source (~> 0.9.0) puma (3.12.1) rack (2.0.6) + rack-mini-profiler (1.0.2) + rack (>= 1.2.0) rack-test (1.1.0) rack (>= 1.0, < 3) rails (5.2.3) @@ -148,6 +151,7 @@ GEM actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) + stackprof (0.2.12) thor (0.20.3) thread_safe (0.3.6) tzinfo (1.2.5) @@ -168,13 +172,16 @@ DEPENDENCIES activerecord-import bootsnap (>= 1.1.0) byebug + flamegraph listen (>= 3.0.5, < 3.2) pg (>= 0.18, < 2.0) pry puma (~> 3.11) + rack-mini-profiler rails (~> 5.2.3) rspec-rails (~> 3.8) rspec-sqlimit + stackprof tzinfo-data web-console (>= 3.3.0) diff --git a/app/controllers/trips_controller.rb b/app/controllers/trips_controller.rb index acb38be..5fc68b4 100644 --- a/app/controllers/trips_controller.rb +++ b/app/controllers/trips_controller.rb @@ -2,6 +2,9 @@ class TripsController < ApplicationController def index @from = City.find_by_name!(params[:from]) @to = City.find_by_name!(params[:to]) - @trips = Trip.where(from: @from, to: @to).order(:start_time) + @trips = Trip.preload(:bus, :services) + .where(from: @from, to: @to) + .select_finish_time + .order(:start_time).load end end diff --git a/app/models/trip.rb b/app/models/trip.rb index 9d63dff..58d9286 100644 --- a/app/models/trip.rb +++ b/app/models/trip.rb @@ -4,6 +4,7 @@ class Trip < ApplicationRecord belongs_to :from, class_name: 'City' belongs_to :to, class_name: 'City' belongs_to :bus + has_many :services, through: :bus validates :from, presence: true validates :to, presence: true @@ -15,6 +16,16 @@ class Trip < ApplicationRecord validates :price_cents, presence: true validates :price_cents, numericality: { greater_than: 0 } + scope :select_finish_time, -> { + select(<<-SQL.squish) + *, + to_char( + start_time::time + (duration_minutes || ' minutes')::interval, + 'HH24:MI' + ) AS finish_time + SQL + } + def to_h { from: from.name, diff --git a/app/views/trips/_services.html.erb b/app/views/trips/_services.html.erb deleted file mode 100644 index 2de639f..0000000 --- a/app/views/trips/_services.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -
  • Сервисы в автобусе:
  • -
      - <% services.each do |service| %> - <%= render "service", service: service %> - <% end %> -
    diff --git a/app/views/trips/_trip.html.erb b/app/views/trips/_trip.html.erb index fa1de9a..06b3782 100644 --- a/app/views/trips/_trip.html.erb +++ b/app/views/trips/_trip.html.erb @@ -1,5 +1,13 @@ -
  • <%= "Отправление: #{trip.start_time}" %>
  • -
  • <%= "Прибытие: #{(Time.parse(trip.start_time) + trip.duration_minutes.minutes).strftime('%H:%M')}" %>
  • -
  • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
  • -
  • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
  • -
  • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
  • +
      +
    • <%= "Отправление: #{trip.start_time}" %>
    • +
    • <%= "Прибытие: #{trip.finish_time}" %>
    • +
    • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
    • +
    • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
    • +
    • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
    • + <% if trip.services.any? %> +
    • Сервисы в автобусе:
    • + <% end %> +
        + <%= render partial: "service", collection: trip.services %> +
      +
    diff --git a/app/views/trips/index.html.erb b/app/views/trips/index.html.erb index a60bce4..648aa4b 100644 --- a/app/views/trips/index.html.erb +++ b/app/views/trips/index.html.erb @@ -2,15 +2,7 @@ <%= "Автобусы #{@from.name} – #{@to.name}" %>

    - <%= "В расписании #{@trips.count} рейсов" %> + <%= "В расписании #{@trips.size} рейсов" %>

    -<% @trips.each do |trip| %> -
      - <%= render "trip", trip: trip %> - <% if trip.bus.services.present? %> - <%= render "services", services: trip.bus.services %> - <% end %> -
    - <%= render "delimiter" %> -<% end %> +<%= render partial: 'trip', collection: @trips, spacer_template: 'delimiter' %> diff --git a/db/migrate/20190509064555_add_from_to_index_to_trips.rb b/db/migrate/20190509064555_add_from_to_index_to_trips.rb new file mode 100644 index 0000000..1863766 --- /dev/null +++ b/db/migrate/20190509064555_add_from_to_index_to_trips.rb @@ -0,0 +1,5 @@ +class AddFromToIndexToTrips < ActiveRecord::Migration[5.2] + def change + add_index :trips, [:from_id, :to_id, :start_time], order: { start_time: :asc } + end +end diff --git a/db/migrate/20190509070919_add_bus_id_index_to_buses_services.rb b/db/migrate/20190509070919_add_bus_id_index_to_buses_services.rb new file mode 100644 index 0000000..e66a0ad --- /dev/null +++ b/db/migrate/20190509070919_add_bus_id_index_to_buses_services.rb @@ -0,0 +1,5 @@ +class AddBusIdIndexToBusesServices < ActiveRecord::Migration[5.2] + def change + add_index :buses_services, :bus_id + end +end diff --git a/db/schema.rb b/db/schema.rb index 8f9a793..af5859a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_05_05_083758) do +ActiveRecord::Schema.define(version: 2019_05_09_074749) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -24,6 +24,7 @@ create_table "buses_services", force: :cascade do |t| t.integer "bus_id" t.integer "service_id" + t.index ["bus_id"], name: "index_buses_services_on_bus_id" end create_table "cities", force: :cascade do |t| @@ -43,6 +44,7 @@ t.integer "duration_minutes" t.integer "price_cents" t.integer "bus_id" + t.index ["from_id", "to_id", "start_time"], name: "index_trips_on_from_id_and_to_id_and_start_time" end end diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake index 38c6c4f..2ad7bbd 100644 --- a/lib/tasks/utils.rake +++ b/lib/tasks/utils.rake @@ -20,7 +20,9 @@ task :reload_json, [:file_name] => :environment do |_task, args| ALTER TABLE buses_services DROP CONSTRAINT buses_services_pkey; DROP INDEX index_cities_on_name; DROP INDEX index_buses_on_number; - DROP INDEX index_services_on_name + DROP INDEX index_services_on_name; + DROP INDEX index_buses_services_on_bus_id; + DROP INDEX index_trips_on_from_id_and_to_id_and_start_time; SQL # add temp columns to trips and import data @@ -65,19 +67,21 @@ task :reload_json, [:file_name] => :environment do |_task, args| BusesService.import([:bus_id, :service_id], buses_services) Object.send(:remove_const, :BusesService) migration.execute('ALTER TABLE buses_services ADD PRIMARY KEY (id);') + migration.add_index(:buses_services, :bus_id) # update trips; remove temp columns; add primary key Trip.where("trips.bus->>'model' = buses.model") .where("trips.bus->>'number' = buses.number") .update_all('bus_id = buses.id FROM buses') - Trip.where("trips.from = services.name") - .update_all('from_id = services.id FROM services') - Trip.where("trips.to = services.name") - .update_all('to_id = services.id FROM services') + Trip.where("trips.from = cities.name") + .update_all('from_id = cities.id FROM cities') + Trip.where("trips.to = cities.name") + .update_all('to_id = cities.id FROM cities') migration.remove_column(:trips, :bus) migration.remove_column(:trips, :from) migration.remove_column(:trips, :to) migration.execute('ALTER TABLE trips ADD PRIMARY KEY (id);') Trip.primary_key = :id + migration.add_index(:trips, [:from_id, :to_id, :start_time], order: { start_time: :asc }) end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 80a1c8f..6395bca 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -6,6 +6,7 @@ abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' require "rspec-sqlimit" +require 'rspec-benchmark' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in @@ -32,6 +33,7 @@ exit 1 end RSpec.configure do |config| + config.include RSpec::Benchmark::Matchers # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" From 71fd3d0c98aa3efdd61dd566232e3bffa3574bf7 Mon Sep 17 00:00:00 2001 From: Stanislav Kravchenko Date: Tue, 14 May 2019 09:09:13 +0300 Subject: [PATCH 8/8] Get rid of partials --- app/controllers/trips_controller.rb | 2 +- app/views/trips/_delimiter.html.erb | 1 - app/views/trips/_service.html.erb | 1 - app/views/trips/_trip.html.erb | 13 ------------- app/views/trips/index.html.erb | 23 +++++++++++++++++++++-- 5 files changed, 22 insertions(+), 18 deletions(-) delete mode 100644 app/views/trips/_delimiter.html.erb delete mode 100644 app/views/trips/_service.html.erb delete mode 100644 app/views/trips/_trip.html.erb diff --git a/app/controllers/trips_controller.rb b/app/controllers/trips_controller.rb index 5fc68b4..83a6f11 100644 --- a/app/controllers/trips_controller.rb +++ b/app/controllers/trips_controller.rb @@ -5,6 +5,6 @@ def index @trips = Trip.preload(:bus, :services) .where(from: @from, to: @to) .select_finish_time - .order(:start_time).load + .order(:start_time)#.load end end diff --git a/app/views/trips/_delimiter.html.erb b/app/views/trips/_delimiter.html.erb deleted file mode 100644 index 3f845ad..0000000 --- a/app/views/trips/_delimiter.html.erb +++ /dev/null @@ -1 +0,0 @@ -==================================================== diff --git a/app/views/trips/_service.html.erb b/app/views/trips/_service.html.erb deleted file mode 100644 index 178ea8c..0000000 --- a/app/views/trips/_service.html.erb +++ /dev/null @@ -1 +0,0 @@ -
  • <%= "#{service.name}" %>
  • diff --git a/app/views/trips/_trip.html.erb b/app/views/trips/_trip.html.erb deleted file mode 100644 index 06b3782..0000000 --- a/app/views/trips/_trip.html.erb +++ /dev/null @@ -1,13 +0,0 @@ -
      -
    • <%= "Отправление: #{trip.start_time}" %>
    • -
    • <%= "Прибытие: #{trip.finish_time}" %>
    • -
    • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
    • -
    • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
    • -
    • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
    • - <% if trip.services.any? %> -
    • Сервисы в автобусе:
    • - <% end %> -
        - <%= render partial: "service", collection: trip.services %> -
      -
    diff --git a/app/views/trips/index.html.erb b/app/views/trips/index.html.erb index 648aa4b..eb452e9 100644 --- a/app/views/trips/index.html.erb +++ b/app/views/trips/index.html.erb @@ -2,7 +2,26 @@ <%= "Автобусы #{@from.name} – #{@to.name}" %>

    - <%= "В расписании #{@trips.size} рейсов" %> + <%= "В расписании #{@trips.count(:all)} рейсов" %>

    -<%= render partial: 'trip', collection: @trips, spacer_template: 'delimiter' %> +<% @trips.find_each.with_index do |trip, index| %> + <% unless index.zero? %> + ==================================================== + <% end %> +
      +
    • <%= "Отправление: #{trip.start_time}" %>
    • +
    • <%= "Прибытие: #{trip.finish_time}" %>
    • +
    • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
    • +
    • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
    • +
    • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
    • + <% if trip.services.any? %> +
    • Сервисы в автобусе:
    • + <% end %> +
        + <% trip.services.each do |service| %> +
      • <%= "#{service.name}" %>
      • + <% end %> +
      +
    +<% end %>