-
Notifications
You must be signed in to change notification settings - Fork 115
Task 3 #119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
elenachekhina
wants to merge
8
commits into
hardcode-dev:master
Choose a base branch
from
elenachekhina:task-3
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Task 3 #119
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
958ee50
add spec
elenachekhina c527ab1
rubocop, rspec
elenachekhina a8fa87d
move logic to service class
elenachekhina bc1104c
json streamer
elenachekhina 3a607f4
json streamer
elenachekhina 7151f82
json streamer
elenachekhina c536943
first part
elenachekhina 9c09458
second part
elenachekhina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,3 +2,4 @@ | |
/tmp | ||
/log | ||
/public | ||
/profile |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
--require spec_helper |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,23 @@ | ||
class TripsController < ApplicationController | ||
before_action :set_pagination_params, :set_cities, only: :index | ||
|
||
def index | ||
@total_count = Trip.where(from: @from, to: @to).count | ||
@trips = Trip.where(from: @from, to: @to) | ||
.order(:start_time) | ||
.limit(@per).offset(@per * (@page - 1)) | ||
.preload(bus: [:services]) | ||
end | ||
|
||
private | ||
|
||
def set_pagination_params | ||
@page = params[:page].present? ? params[:page].to_i : 1 | ||
@per = params[:per].present? ? params[:per].to_i : 100 | ||
end | ||
|
||
def set_cities | ||
@from = City.find_by_name!(params[:from]) | ||
@to = City.find_by_name!(params[:to]) | ||
@trips = Trip.where(from: @from, to: @to).order(:start_time) | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
class BusesService < ApplicationRecord | ||
belongs_to :bus | ||
belongs_to :service | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
# frozen_string_literal: true | ||
|
||
class DataLoader | ||
TRIPS_COMMAND = | ||
"copy trips (from_id, to_id, start_time, duration_minutes, price_cents, bus_id) from stdin with csv delimiter ';'" | ||
CITIES_COMMAND = "copy cities (id, name) from stdin with csv delimiter ';'" | ||
BUSES_COMMAND = "copy buses (id, number, model) from stdin with csv delimiter ';'" | ||
SERVICES_COMMAND = "copy services (id, name) from stdin with csv delimiter ';'" | ||
BUSES_SERVICES_COMMAND = "copy buses_services (bus_id, service_id) from stdin with csv delimiter ';'" | ||
|
||
def self.load(filename) | ||
new(filename).load | ||
end | ||
|
||
def initialize(filename) | ||
@stream = JsonStreamer.stream(filename) | ||
@cities = {} | ||
@services = {} | ||
@buses = {} | ||
@buses_services = [] | ||
end | ||
|
||
def load | ||
ActiveRecord::Base.transaction do | ||
clean_database | ||
connection = ActiveRecord::Base.connection.raw_connection | ||
|
||
ActiveRecord::Base.connection.raw_connection.copy_data TRIPS_COMMAND do | ||
stream.each do |trip| | ||
from = city(trip['from']) | ||
to = city(trip['to']) | ||
|
||
if buses[trip['bus']['number']].nil? | ||
bus_services = [] | ||
trip['bus']['services'].each do |name| | ||
bus_services << service(name) | ||
end | ||
|
||
create_bus(trip['bus']['number'], trip['bus']['model']) | ||
create_bus_services(buses[trip['bus']['number']], bus_services) | ||
end | ||
|
||
bus = buses[trip['bus']['number']] | ||
|
||
connection.put_copy_data("#{from[:id]};#{to[:id]};#{trip['start_time']};#{trip['duration_minutes']};#{trip['price_cents']};#{bus[:id]}\n") | ||
end | ||
end | ||
|
||
ActiveRecord::Base.connection.raw_connection.copy_data CITIES_COMMAND do | ||
cities.each do |name, attrs| | ||
connection.put_copy_data("#{attrs[:id]};#{name}\n") | ||
end | ||
end | ||
|
||
ActiveRecord::Base.connection.raw_connection.copy_data BUSES_COMMAND do | ||
buses.each do |number, attrs| | ||
connection.put_copy_data("#{attrs[:id]};#{number};#{attrs[:model]}\n") | ||
end | ||
end | ||
|
||
ActiveRecord::Base.connection.raw_connection.copy_data SERVICES_COMMAND do | ||
services.each do |name, attrs| | ||
connection.put_copy_data("#{attrs[:id]};#{name}\n") | ||
end | ||
end | ||
|
||
ActiveRecord::Base.connection.raw_connection.copy_data BUSES_SERVICES_COMMAND do | ||
buses_services.each do |bus_id, service_id| | ||
connection.put_copy_data("#{bus_id};#{service_id}\n") | ||
end | ||
end | ||
end | ||
end | ||
|
||
private | ||
|
||
attr_reader :stream | ||
attr_accessor :cities, :services, :buses, :buses_services | ||
|
||
def clean_database | ||
City.delete_all | ||
Bus.delete_all | ||
Service.delete_all | ||
Trip.delete_all | ||
ActiveRecord::Base.connection.execute('delete from buses_services;') | ||
end | ||
|
||
def city(name) | ||
cities[name] ||= { id: cities.size + 1 } | ||
end | ||
|
||
def service(name) | ||
services[name] ||= { id: services.size + 1 } | ||
end | ||
|
||
def create_bus(number, model) | ||
buses[number] = { id: buses.size + 1, model: } | ||
end | ||
|
||
def create_bus_services(bus, services) | ||
services.map do |service| | ||
@buses_services << [bus[:id], service[:id]] | ||
end | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# frozen_string_literal: true | ||
|
||
class JsonStreamer | ||
def self.stream(filename) | ||
new(filename).stream | ||
end | ||
|
||
def initialize(filename) | ||
@file = File.open(filename, 'r:UTF-8') | ||
end | ||
|
||
def stream | ||
Enumerator.new do |yielder| | ||
loop do | ||
yielder << Oj.load(object) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 ого, найс |
||
rescue Oj::ParseError, TypeError => _e | ||
break | ||
end | ||
end | ||
end | ||
|
||
private | ||
|
||
attr_reader :file | ||
|
||
def object | ||
nesting = 0 | ||
str = +'' | ||
|
||
while nesting > 0 || str.empty? | ||
ch = file.getc | ||
|
||
return if file.eof? | ||
|
||
nesting += 1 if ch == '{' | ||
str << ch if nesting >= 1 | ||
nesting -= 1 if ch == '}' | ||
|
||
str | ||
end | ||
|
||
str | ||
end | ||
end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
пагинация limit offset в целом имеет для меня плохую репутацию (вроде бы про это что-то было в лекциях)
Trip.where(from: @from, to: @to).count
при большом кол-ве трипов может начать жёстко тормозить, что негативно скажется на времени загрузки страницы (у нас тут их так много нет, но сам паттерн такой пагинации потенциально проблемный)