rubbish_code 0.1.0 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b4b21965f0130ca61a48365f3da378ad726bf29a211ee6d2327cc825e0eb8449
4
- data.tar.gz: b19d9d9517f6a90fa30f7ac0e0426e71d34a0a3d80e29e59e1105f439884fb70
3
+ metadata.gz: 2dafe2051c5e2de11d72e00a434486b1bd66b1914411ac64b216918181f7fa8b
4
+ data.tar.gz: 0216bdf9531c3876cc9ee8667641e8178fb16c9f6427ee5c5f30fcc344510af5
5
5
  SHA512:
6
- metadata.gz: eb08de61aa853a490678f922b6ef29ccbf30af3e00f3f9cd3a50ab98db4feae77b0a2f99f5301601712dd7f13112d1b9fb5c1fe6b6abf50148c8d006c435c8ee
7
- data.tar.gz: b6e3c9963cc335cb5b957c7fbda8ce9e80d639b6021016b607a1a179131a2dfc5732217d1818879f24f7e41477846db7e5c573f5d2fa1923110bb8e34a2b39ab
6
+ metadata.gz: 81862c94d927737e281b8c0fb394a01f3a94ac9a496646ec24649a8cd0dc3b32b9134fbd220d5b56a2cc5027d2206ded5b443187e7f3013794451271fbf054d5
7
+ data.tar.gz: 5faf849675ce3e4d28408ea9375f20ecab248e10fa7eaa780fd4cf474f55d9a5bedf97b106684fdcf614d432096005bce44d78a3ba1b983d12733e5cee2fbb71
data/Documentation.md ADDED
@@ -0,0 +1,33 @@
1
+ The TabStudentsController class is a controller for working with the interface for interacting with objects of the Student type.
2
+
3
+ Methods of the class:
4
+
5
+ 1. initialize(view) - constructor of the class, takes a view object and creates an empty object of the type
6
+ DataListStudentShort, which is assigned the add_listener method with the view argument, as a result of which the view
7
+ is set as a listener for data state change events (data_list).
8
+ 2. on_view_created is a method that initializes an object of the StudentRepository type, which is used for interaction
9
+ with the database, and if an error occurs connecting to the database displays a dialog box with an error message.
10
+ 3. show_view is a method that displays the main application window.
11
+ 4. show_modal_add is a method that displays a modal window for creating a new student record.
12
+ Creates an instance of the StudentInputFormControllerCreate controller and passes it a reference to the current controller,
13
+ creates an object of the StudentInputForm type and passes it a reference to the controller. Then it displays the modal window.
14
+ 5. show_modal_edit(current_page, per_page, selected_row) is a method that displays the modal window for
15
+ editing a student record. Takes the values of the current page (current_page), the number of records on the page
16
+ (per_page) and the selected row (selected_row). Calculates the number of the selected student and selects his id from
17
+ the DataListStudentShort object, then passes it to the StudentInputFormControllerEdit controller, creates an object of the type
18
+ StudentInputForm and passes it a link to the controller. After that, it displays a modal window.
19
+ 6. delete_selected(current_page, per_page, selected_row) is a method that deletes the selected student record.
20
+ Takes the values of the current page (current_page), the number of records on the page (per_page)
21
+ and the selected row (selected_row). Calculates the number of the selected student and selects his id from the DataListStudentShort object,
22
+ then deletes the record using the remove_student method from the StudentRepository object.
23
+ 7. refresh_data(page, per_page) is a method that updates the data in the list of students. Takes the values
24
+ of the current page (page) and the number of entries on the page (per_page).
25
+ Calls a method of the StudentRepository paginated_short_students type to get data in the DataListStudentShort object format.
26
+ Updates information about the number of students using the update_student_count method of the view.
27
+
28
+ The Student_Input_Form_Controller_Edit controller and Student_Input_Form_Controller_Create are forms
29
+ for modifying and creating students into the database, respectively.
30
+
31
+ The student, student_base and student_short models are a student model with various fields and methods
32
+ for setting, receiving and processing information. Student_base - super class,
33
+ and student_short is the short information about the student.
data/LICENSE.txt CHANGED
@@ -2,36 +2,20 @@ MIT License
2
2
 
3
3
  Copyright (c) 2023 NullExp
4
4
 
5
- Класс TabStudentsController представляет собой контроллер для работы с интерфейсом взаимодействия с объектами типа Student.
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
6
11
 
7
- Методы класса:
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
8
14
 
9
- 1. initialize(view) - конструктор класса, принимает объект представления (view) и создает пустой объект типа
10
- DataListStudentShort, которому присваивается метод add_listener с аргументом view, в результате чего представление
11
- устанавливается в качестве слушателя событий изменения состояния данных (data_list).
12
- 2. on_view_created - метод, инициализирующий объект типа StudentRepository, который используется для взаимодействия
13
- с базой данных, и при возникновении ошибки подключения к базе выводит диалоговое окно с сообщением об ошибке.
14
- 3. show_view - метод, отображающий основное окно приложения.
15
- 4. show_modal_add - метод, отображающий модальное окно для создания новой записи о студенте.
16
- Создает экземпляр контроллера StudentInputFormControllerCreate и передает ему ссылку на текущий контроллер,
17
- создает объект типа StudentInputForm и передает ему ссылку на контроллер. После чего отображает модальное окно.
18
- 5. show_modal_edit(current_page, per_page, selected_row) - метод, отображающий модальное окно для
19
- редактирования записи о студенте. Принимает значения текущей страницы (current_page), количества записей на странице
20
- (per_page) и выбранной строки (selected_row). Вычисляет номер выбранного студента и выбирает его id из
21
- объекта DataListStudentShort, после чего передает его в контроллер StudentInputFormControllerEdit, создает объект типа
22
- StudentInputForm и передает ему ссылку на контроллер. После чего отображает модальное окно.
23
- 6. delete_selected(current_page, per_page, selected_row) - метод, удаляющий выбранную запись о студенте.
24
- Принимает значения текущей страницы (current_page), количества записей на странице (per_page)
25
- и выбранной строки (selected_row). Вычисляет номер выбранного студента и выбирает его id из объекта DataListStudentShort,
26
- после чего удаляет запись с помощью метода remove_student из объекта типа StudentRepository.
27
- 7. refresh_data(page, per_page) - метод, обновляющий данные в списке студентов. Принимает значения
28
- текущей страницы (page) и количества записей на странице (per_page).
29
- Вызывает метод типа StudentRepository paginated_short_students для получения данных в формате объекта DataListStudentShort.
30
- Обновляет информацию о количестве студентов с помощью метода update_student_count представления.
31
-
32
- Контроллер Student_Input_Form_Controller_Edit и Student_Input_Form_Controller_Create представляют собой формы
33
- для изменения и создания студентов в базу данных, соотвественно.
34
-
35
- Модели student, student_base и student_short представляет собой модель студента с различными полями и методами
36
- для установки, получения и обработки информации. Student_base - супер класс,
37
- а student_short - короктая информация о студенте.
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -7,28 +7,29 @@ require './LabStudents/repositories/containers/data_list_student_short'
7
7
  require './LabStudents/views/student_input_form'
8
8
  require './LabStudents/controllers/student_input_form/student_input_form_controller_create'
9
9
  require './LabStudents/controllers/student_input_form/student_input_form_controller_edit'
10
+ require './LabStudents/util/logger_holder'
10
11
  require 'win32api'
11
12
 
12
13
  class TabStudentsController
13
14
  def initialize(view)
15
+ LoggerHolder.instance.debug('TabStudentsController: init start')
14
16
  @view = view
15
17
  @data_list = DataListStudentShort.new([])
16
18
  @data_list.add_listener(@view)
19
+ LoggerHolder.instance.debug('TabStudentsController: init done')
17
20
  end
18
21
 
19
22
  def on_view_created
20
- #begin
23
+ begin
21
24
  @student_rep = StudentRepository.new(DBSourceAdapter.new)
22
- # rescue Mysql2::Error::ConnectionError
23
- # on_db_conn_error
24
- # end
25
- end
26
-
27
- def show_view
28
- @view.create.show
25
+ LoggerHolder.instance.debug('TabStudentsController: created student repository')
26
+ rescue Mysql2::Error::ConnectionError => e
27
+ on_db_conn_error(e)
28
+ end
29
29
  end
30
30
 
31
31
  def show_modal_add
32
+ LoggerHolder.instance.debug('TabStudentsController: showing modal (add)')
32
33
  controller = StudentInputFormControllerCreate.new(self)
33
34
  view = StudentInputForm.new(controller)
34
35
  controller.set_view(view)
@@ -36,6 +37,7 @@ class TabStudentsController
36
37
  end
37
38
 
38
39
  def show_modal_edit(current_page, per_page, selected_row)
40
+ LoggerHolder.instance.debug('TabStudentsController: showing modal (edit)')
39
41
  student_num = (current_page - 1) * per_page + selected_row
40
42
  @data_list.select_element(student_num)
41
43
  student_id = @data_list.selected_id
@@ -46,30 +48,35 @@ class TabStudentsController
46
48
  end
47
49
 
48
50
  def delete_selected(current_page, per_page, selected_row)
49
- #begin
51
+ begin
52
+ LoggerHolder.instance.debug('TabStudentsController: deleting selected student')
50
53
  student_num = (current_page - 1) * per_page + selected_row
51
54
  @data_list.select_element(student_num)
52
55
  student_id = @data_list.selected_id
53
56
  @student_rep.remove_student(student_id)
54
- # rescue
55
- # on_db_conn_error
56
- # end
57
+ rescue Mysql2::Error::ConnectionError => e
58
+ on_db_conn_error(e)
59
+ end
57
60
  end
58
61
 
59
62
  def refresh_data(page, per_page)
60
- #begin
63
+ begin
64
+ LoggerHolder.instance.debug('TabStudentsController: refreshing data...')
61
65
  @data_list = @student_rep.paginated_short_students(page, per_page, @data_list)
62
66
  @view.update_student_count(@student_rep.student_count)
63
- # rescue
64
- # on_db_conn_error
65
- # end
67
+ rescue Mysql2::Error::ConnectionError => e
68
+ on_db_conn_error(e)
69
+ end
66
70
  end
67
71
 
68
72
  private
69
73
 
70
- def on_db_conn_error
71
- # api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
72
- # api.call(0, "No connection to DB =)", "Error", 0)
73
- # exit(false)
74
+ def on_db_conn_error(error)
75
+ LoggerHolder.instance.error('TabStudentsController: DB connection error:')
76
+ LoggerHolder.instance.error(error.message)
77
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
78
+ api.call(0, "No connection to DB", "Error", 0)
79
+ # TODO: Возможность переключения на JSON помимо exit
80
+ exit(false)
74
81
  end
75
82
  end
@@ -0,0 +1,5 @@
1
+ host: 'localhost'
2
+ port: 3306
3
+ username: 'root'
4
+ password: '1234'
5
+ database: 'university'
@@ -0,0 +1,12 @@
1
+ create table student (
2
+ id int auto_increment,
3
+ last_name varchar(128) not null,
4
+ first_name varchar(128) not null,
5
+ father_name varchar(128) not null,
6
+ phone varchar(20) null,
7
+ telegram varchar(100) null,
8
+ email varchar(100) null,
9
+ git varchar(100) null,
10
+ constraint student_pk
11
+ primary key (id)
12
+ );
@@ -0,0 +1,71 @@
1
+ require 'test/unit'
2
+ require_relative 'student'
3
+
4
+ class TestStudent < Test::Unit::TestCase
5
+ def setup
6
+ @student = Student.new('Иванов', 'Иван', 'Иванович')
7
+ end
8
+
9
+ def test_full_name
10
+ assert_equal('Иванов Иван Иванович', @student.to_s.split(', ')[0])
11
+ end
12
+
13
+ def test_contacts
14
+ @student = Student.new('Иванов', 'Иван', 'Иванович')
15
+ @student.set_contacts(phone: '+79991234567', email: 'ivanov@example.com')
16
+ assert_equal('+79991234567', @student.phone)
17
+ assert_equal('ivanov@example.com', @student.email)
18
+ end
19
+
20
+ def test_valid_name
21
+ assert(Student.valid_name?('Иванов'))
22
+ assert(!Student.valid_name?('Сидоров-Петров'))
23
+ assert(!Student.valid_name?('X'))
24
+ assert(Student.valid_name?('Abcdefghijklmnopqrstuvwxyz'))
25
+ assert(!Student.valid_name?(''))
26
+ assert(!Student.valid_name?('Иванов 123'))
27
+ assert(!Student.valid_name?('Иванов.'))
28
+ assert(!Student.valid_name?('-Иванов'))
29
+ end
30
+
31
+ def test_from_hash
32
+ hash = {
33
+ first_name: 'Иван',
34
+ last_name: 'Иванов',
35
+ father_name: 'Иванович',
36
+ phone: '+79991234567',
37
+ telegram: 'ivanov',
38
+ email: 'ivanov@example.com',
39
+ git: 'ivanov'
40
+ }
41
+ student = Student.from_hash(hash)
42
+ assert_equal(hash[:first_name], student.first_name)
43
+ assert_equal(hash[:last_name], student.last_name)
44
+ assert_equal(hash[:father_name], student.father_name)
45
+ assert_equal(hash[:phone], student.phone)
46
+ assert_equal(hash[:telegram], student.telegram)
47
+ assert_equal(hash[:email], student.email)
48
+ assert_equal(hash[:git], student.git)
49
+ end
50
+
51
+ def test_from_json_str
52
+ hash = {
53
+ first_name: 'Иван',
54
+ last_name: 'Иванов',
55
+ father_name: 'Иванович',
56
+ phone: '+79991234567',
57
+ telegram: 'ivanov',
58
+ email: 'ivanov@example.com',
59
+ git: 'ivanov'
60
+ }
61
+ json_str = hash.to_json
62
+ student = Student.from_json_str(json_str)
63
+ assert_equal(hash[:first_name], student.first_name)
64
+ assert_equal(hash[:last_name], student.last_name)
65
+ assert_equal(hash[:father_name], student.father_name)
66
+ assert_equal(hash[:phone], student.phone)
67
+ assert_equal(hash[:telegram], student.telegram)
68
+ assert_equal(hash[:email], student.email)
69
+ assert_equal(hash[:git], student.git)
70
+ end
71
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ class StudentRepository
4
+ def initialize(data_source_adapter)
5
+ @data_source_adapter = data_source_adapter
6
+ end
7
+
8
+ def student_by_id(student_id)
9
+ @data_source_adapter.student_by_id(student_id)
10
+ end
11
+
12
+ # Получить page по счету count элементов (страница начинается с 1)
13
+ def paginated_short_students(page, count, existing_data_list = nil)
14
+ @data_source_adapter.paginated_short_students(page, count, existing_data_list)
15
+ end
16
+
17
+ def add_student(student)
18
+ @data_source_adapter.add_student(student)
19
+ end
20
+
21
+ def replace_student(student_id, student)
22
+ @data_source_adapter.replace_student(student_id, student)
23
+ end
24
+
25
+ def remove_student(student_id)
26
+ @data_source_adapter.remove_student(student_id)
27
+ end
28
+
29
+ def student_count
30
+ @data_source_adapter.student_count
31
+ end
32
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'logger'
4
+
5
+ class LoggerHolder
6
+ private_class_method :new
7
+ @instance_mutex = Mutex.new
8
+
9
+ attr_reader :logger
10
+
11
+ def initialize
12
+ @logger = Logger.new(STDOUT)
13
+ end
14
+
15
+ def self.instance
16
+ return @instance.logger if @instance
17
+
18
+ @instance_mutex.synchronize do
19
+ @instance ||= new
20
+ end
21
+
22
+ @instance.logger
23
+ end
24
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubbish_code
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jake Epps
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2023-05-05 00:00:00.000000000 Z
11
+ date: 2023-05-09 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: win32api
@@ -30,14 +30,18 @@ executables: []
30
30
  extensions: []
31
31
  extra_rdoc_files: []
32
32
  files:
33
+ - Documentation.md
33
34
  - LICENSE.txt
34
35
  - README.md
35
- - lib/controllers/student_input_form/student_input_form_controller_create.rb
36
- - lib/controllers/student_input_form/student_input_form_controller_edit.rb
37
- - lib/controllers/tab_students_controller.rb
38
- - lib/models/student.rb
39
- - lib/models/student_base.rb
40
- - lib/models/student_short.rb
36
+ - controllers/tab_students_controller.rb
37
+ - db_config/config.yaml
38
+ - db_config/migrations/001_create_table_student.sql
39
+ - models/student.rb
40
+ - models/student_base.rb
41
+ - models/student_short.rb
42
+ - models/student_test.rb
43
+ - repositories/student_repository.rb
44
+ - util/logger_holder.rb
41
45
  homepage: https://github.com/Jakepps/Ruby_Moment
42
46
  licenses:
43
47
  - MIT
@@ -50,7 +54,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
50
54
  requirements:
51
55
  - - ">="
52
56
  - !ruby/object:Gem::Version
53
- version: '0'
57
+ version: '3.0'
54
58
  required_rubygems_version: !ruby/object:Gem::Requirement
55
59
  requirements:
56
60
  - - ">="
@@ -1,48 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'win32api'
4
-
5
- class StudentInputFormControllerCreate
6
- def initialize(parent_controller)
7
- @parent_controller = parent_controller
8
- end
9
-
10
- def set_view(view)
11
- @view = view
12
- end
13
-
14
- def on_view_created
15
- begin
16
- @student_rep = StudentRepository.new(DBSourceAdapter.new)
17
- rescue Mysql2::Error::ConnectionError
18
- on_db_conn_error
19
- end
20
- end
21
-
22
- def process_fields(fields)
23
- begin
24
- last_name = fields.delete(:last_name)
25
- first_name = fields.delete(:first_name)
26
- father_name = fields.delete(:father_name)
27
-
28
- return if last_name.nil? || first_name.nil? || father_name.nil?
29
-
30
- student = Student.new(last_name, first_name, father_name, **fields)
31
-
32
- @student_rep.add_student(student)
33
-
34
- @view.close
35
- rescue ArgumentError => e
36
- api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
37
- api.call(0, e.message, 'Error', 0)
38
- end
39
- end
40
-
41
- private
42
-
43
- def on_db_conn_error
44
- api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
45
- api.call(0, "No connection to DB говно", "Error", 0)
46
- @view.close
47
- end
48
- end
@@ -1,56 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'win32api'
4
-
5
- class StudentInputFormControllerEdit
6
- def initialize(parent_controller, existing_student_id)
7
- @parent_controller = parent_controller
8
- @existing_student_id = existing_student_id
9
- end
10
-
11
- def set_view(view)
12
- @view = view
13
- end
14
-
15
- def on_view_created
16
- begin
17
- @student_rep = StudentRepository.new(DBSourceAdapter.new)
18
- rescue Mysql2::Error::ConnectionError
19
- on_db_conn_error
20
- end
21
- @existing_student = @student_rep.student_by_id(@existing_student_id)
22
- #@view.make_readonly(:git, :telegram, :email, :phone)
23
- populate_fields(@existing_student)
24
- end
25
-
26
- def populate_fields(student)
27
- @view.set_value(:last_name, student.last_name)
28
- @view.set_value(:first_name, student.first_name)
29
- @view.set_value(:father_name, student.father_name)
30
- @view.set_value(:git, student.git)
31
- @view.set_value(:telegram, student.telegram)
32
- @view.set_value(:email, student.email)
33
- @view.set_value(:phone, student.phone)
34
- end
35
-
36
- def process_fields(fields)
37
- begin
38
- new_student = Student.from_hash(fields)
39
-
40
- @student_rep.replace_student(@existing_student_id, new_student)
41
-
42
- @view.close
43
- rescue ArgumentError => e
44
- api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
45
- api.call(0, e.message, 'Error', 0)
46
- end
47
- end
48
-
49
- private
50
-
51
- def on_db_conn_error
52
- api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
53
- api.call(0, "No connection to DB", "Error", 0)
54
- @view.close
55
- end
56
- end
File without changes
File without changes
File without changes