shnaider_code 1.1.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (33) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/CODE_OF_CONDUCT.md +84 -0
  4. data/Documentation.md +33 -0
  5. data/Gemfile +13 -0
  6. data/Gemfile.lock +92 -0
  7. data/lib/shnaider_code/version.rb +5 -0
  8. data/lib/shnaider_code.rb +10 -0
  9. data/lib/source/controllers/student_input_form/student_input_form_controller_create.rb +68 -0
  10. data/lib/source/controllers/student_input_form/student_input_form_controller_edit.rb +78 -0
  11. data/lib/source/controllers/tab_students_controller.rb +104 -0
  12. data/lib/source/db_config/config.example.yaml +5 -0
  13. data/lib/source/db_config/migrations/001_create_table_student.sql +12 -0
  14. data/lib/source/db_config/mock_data/fill_student.sql +6 -0
  15. data/lib/source/models/student.rb +125 -0
  16. data/lib/source/models/student_base.rb +128 -0
  17. data/lib/source/models/student_short.rb +58 -0
  18. data/lib/source/repositories/adapters/db_source_adapter.rb +54 -0
  19. data/lib/source/repositories/adapters/file_source_adapter.rb +37 -0
  20. data/lib/source/repositories/containers/data_list.rb +74 -0
  21. data/lib/source/repositories/containers/data_list_student_short.rb +18 -0
  22. data/lib/source/repositories/containers/data_table.rb +35 -0
  23. data/lib/source/repositories/data_sources/db_data_source.rb +35 -0
  24. data/lib/source/repositories/data_sources/file_data_source.rb +77 -0
  25. data/lib/source/repositories/data_sources/transformers/data_transformer_base.rb +15 -0
  26. data/lib/source/repositories/data_sources/transformers/data_transformer_json.rb +16 -0
  27. data/lib/source/repositories/data_sources/transformers/data_transformer_yaml.rb +16 -0
  28. data/lib/source/repositories/student_repository.rb +37 -0
  29. data/lib/source/util/logger_holder.rb +29 -0
  30. data/shnaider_code-1.1.4.gem +0 -0
  31. data/shnaider_code.gemspec +17 -0
  32. data/sig/shnaider_code.rbs +4 -0
  33. metadata +88 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b0f2d61075e4ea8ed4bd5251fdede22a0852304e235b35286e29162649ef9748
4
+ data.tar.gz: ebc0f80b93bcb4c885da7370b2c42943c2b99bfe5f67237dc1eb3918a975b2ab
5
+ SHA512:
6
+ metadata.gz: bfaa925bb39c18ab6937f9d0d5686f58b04083bc00bc941bc0fae3de3aab27daf4367dcd989221147b4256ebd8c9b46258d5f07e602e92c44711cc963b98a797
7
+ data.tar.gz: 300d64689ec07620cd2f11d802c221072546a66799739e4d1749914b176e50ece0fc898405257f63b95b06ffc6b32223420a271cdd6e645be48aac805e19ecca
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-04-28
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at delta.null@vk.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
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/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gem "mysql2"
6
+ gem "glimmer-dsl-libui",'~> 0.7.4'
7
+ gem 'win32api'
8
+ gem "minitest"
9
+ gem 'rubocop', group: 'development'
10
+ # gem 'shnaider_code', '~> 0.1.3'
11
+ gem 'shnaider_code'
12
+ gem 'sinatra', '~> 3.0', '>= 3.0.6'
13
+ gem 'thin', '~> 1.8', '>= 1.8.2'
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ GEM
2
+ remote: https://rubygems.org/
3
+ specs:
4
+ array_include_methods (1.4.0)
5
+ ast (2.4.2)
6
+ chunky_png (1.4.0)
7
+ color (1.8)
8
+ daemons (1.4.1)
9
+ equalizer (0.0.11)
10
+ eventmachine (1.2.7)
11
+ facets (3.1.0)
12
+ glimmer (2.7.3)
13
+ array_include_methods (~> 1.4.0)
14
+ facets (>= 3.1.0, < 4.0.0)
15
+ glimmer-dsl-libui (0.7.7)
16
+ chunky_png (~> 1.4.0)
17
+ color (~> 1.8)
18
+ equalizer (= 0.0.11)
19
+ glimmer (~> 2.7.3)
20
+ libui (~> 0.1.2.pre)
21
+ os (>= 1.0.0, < 2.0.0)
22
+ perfect-shape (~> 1.0.7)
23
+ rouge (>= 3.26.0, < 4.0.0)
24
+ super_module (~> 1.4.1)
25
+ json (2.6.3)
26
+ libui (0.1.2.pre-x64-mingw)
27
+ matrix (0.4.2)
28
+ method_source (1.0.0)
29
+ minitest (5.18.0)
30
+ mustermann (3.0.0)
31
+ ruby2_keywords (~> 0.0.1)
32
+ mysql2 (0.5.5)
33
+ os (1.1.4)
34
+ parallel (1.23.0)
35
+ parser (3.2.2.1)
36
+ ast (~> 2.4.1)
37
+ perfect-shape (1.0.7)
38
+ equalizer (>= 0.0.11, < 1.1.0)
39
+ matrix (>= 0.4.2, < 1.1.0)
40
+ rack (2.2.7)
41
+ rack-protection (3.0.6)
42
+ rack
43
+ rainbow (3.1.1)
44
+ regexp_parser (2.8.0)
45
+ rexml (3.2.5)
46
+ rouge (3.30.0)
47
+ rubocop (1.51.0)
48
+ json (~> 2.3)
49
+ parallel (~> 1.10)
50
+ parser (>= 3.2.0.0)
51
+ rainbow (>= 2.2.2, < 4.0)
52
+ regexp_parser (>= 1.8, < 3.0)
53
+ rexml (>= 3.2.5, < 4.0)
54
+ rubocop-ast (>= 1.28.0, < 2.0)
55
+ ruby-progressbar (~> 1.7)
56
+ unicode-display_width (>= 2.4.0, < 3.0)
57
+ rubocop-ast (1.28.1)
58
+ parser (>= 3.2.1.0)
59
+ ruby-progressbar (1.13.0)
60
+ ruby2_keywords (0.0.5)
61
+ shnaider_code (1.1.4)
62
+ win32api
63
+ sinatra (3.0.6)
64
+ mustermann (~> 3.0)
65
+ rack (~> 2.2, >= 2.2.4)
66
+ rack-protection (= 3.0.6)
67
+ tilt (~> 2.0)
68
+ super_module (1.4.1)
69
+ method_source (>= 0.8.2, < 1.1.0)
70
+ thin (1.8.2)
71
+ daemons (~> 1.0, >= 1.0.9)
72
+ eventmachine (~> 1.0, >= 1.0.4)
73
+ rack (>= 1, < 3)
74
+ tilt (2.1.0)
75
+ unicode-display_width (2.4.2)
76
+ win32api (0.1.0)
77
+
78
+ PLATFORMS
79
+ x64-mingw-ucrt
80
+
81
+ DEPENDENCIES
82
+ glimmer-dsl-libui (~> 0.7.4)
83
+ minitest
84
+ mysql2
85
+ rubocop
86
+ shnaider_code
87
+ sinatra (~> 3.0, >= 3.0.6)
88
+ thin (~> 1.8, >= 1.8.2)
89
+ win32api
90
+
91
+ BUNDLED WITH
92
+ 2.4.10
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ShnaiderCode
4
+ VERSION = "1.1.5"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "shnaider_code/version"
4
+
5
+ module ShnaiderCode
6
+ Dir[File.dirname(__FILE__) + '/source/**/*.rb'].each { |file|
7
+ puts file
8
+ require file
9
+ }
10
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require './LabStudents/util/logger_holder'
4
+ require 'win32api'
5
+
6
+ ##
7
+ # Контроллер для модального окна создания студента
8
+
9
+ class StudentInputFormControllerCreate
10
+ def initialize(parent_controller)
11
+ @parent_controller = parent_controller
12
+ LoggerHolder.instance.debug('StudentInputFormControllerCreate: initialized')
13
+ end
14
+
15
+ def set_view(view)
16
+ @view = view
17
+ LoggerHolder.instance.debug('StudentInputFormControllerCreate: view set')
18
+ end
19
+
20
+ ##
21
+ # Вызывается из view после ее создания
22
+
23
+ def on_view_created
24
+ begin
25
+ @student_rep = StudentRepository.new(DBSourceAdapter.new)
26
+ rescue Mysql2::Error::ConnectionError => e
27
+ on_db_conn_error(e)
28
+ end
29
+ end
30
+
31
+ ##
32
+ # Обработать данные из полей и добавить студента
33
+
34
+ def process_fields(fields)
35
+ begin
36
+ last_name = fields.delete(:last_name)
37
+ first_name = fields.delete(:first_name)
38
+ father_name = fields.delete(:father_name)
39
+
40
+ return if last_name.nil? || first_name.nil? || father_name.nil?
41
+
42
+ student = Student.new(last_name, first_name, father_name, **fields)
43
+
44
+ LoggerHolder.instance.debug('StudentInputFormControllerCreate: adding student to DB')
45
+
46
+ @student_rep.add_student(student)
47
+
48
+ @view.close
49
+ rescue ArgumentError => e
50
+ LoggerHolder.instance.debug("StudentInputFormControllerCreate: wrong fields: #{e.message}")
51
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
52
+ api.call(0, e.message, 'Error', 0)
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ ##
59
+ # Обработчик ошибки подключения к БД
60
+
61
+ def on_db_conn_error(error)
62
+ LoggerHolder.instance.debug('StudentInputFormControllerCreate: DB connection error:')
63
+ LoggerHolder.instance.error(error.message)
64
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
65
+ api.call(0, "No connection to DB", "Error", 0)
66
+ @view.close
67
+ end
68
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require './LabStudents/util/logger_holder'
4
+ require 'win32api'
5
+
6
+ ##
7
+ # Контроллер для модального окна изменения студента
8
+
9
+ class StudentInputFormControllerEdit
10
+ def initialize(parent_controller, existing_student_id)
11
+ @parent_controller = parent_controller
12
+ @existing_student_id = existing_student_id
13
+ LoggerHolder.instance.debug('StudentInputFormControllerEdit: initialized')
14
+ end
15
+
16
+ def set_view(view)
17
+ @view = view
18
+ LoggerHolder.instance.debug('StudentInputFormControllerEdit: view set')
19
+ end
20
+
21
+ ##
22
+ # Вызывается из view после ее создания
23
+
24
+ def on_view_created
25
+ begin
26
+ @student_rep = StudentRepository.new(DBSourceAdapter.new)
27
+ rescue Mysql2::Error::ConnectionError => e
28
+ on_db_conn_error(e)
29
+ end
30
+ @existing_student = @student_rep.student_by_id(@existing_student_id)
31
+ @view.make_readonly(:git, :telegram, :email, :phone)
32
+ populate_fields(@existing_student)
33
+ end
34
+
35
+ ##
36
+ # Заполнить имеющиеся данные о студенте
37
+
38
+ def populate_fields(student)
39
+ @view.set_value(:last_name, student.last_name)
40
+ @view.set_value(:first_name, student.first_name)
41
+ @view.set_value(:father_name, student.father_name)
42
+ @view.set_value(:git, student.git)
43
+ @view.set_value(:telegram, student.telegram)
44
+ @view.set_value(:email, student.email)
45
+ @view.set_value(:phone, student.phone)
46
+ end
47
+
48
+ ##
49
+ # Обработать данные из полей и добавить студента
50
+
51
+ def process_fields(fields)
52
+ begin
53
+ new_student = Student.from_hash(fields)
54
+
55
+ LoggerHolder.instance.debug('StudentInputFormControllerEdit: replacing student in DB')
56
+
57
+ @student_rep.replace_student(@existing_student_id, new_student)
58
+
59
+ @view.close
60
+ rescue ArgumentError => e
61
+ LoggerHolder.instance.debug("StudentInputFormControllerEdit: wrong fields: #{e.message}")
62
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
63
+ api.call(0, e.message, 'Error', 0)
64
+ end
65
+ end
66
+
67
+ private
68
+
69
+ ##
70
+ # Обработчик ошибки подключения к БД
71
+ def on_db_conn_error(error)
72
+ LoggerHolder.instance.debug('StudentInputFormControllerEdit: DB connection error:')
73
+ LoggerHolder.instance.error(error.message)
74
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
75
+ api.call(0, "No connection to DB", "Error", 0)
76
+ @view.close
77
+ end
78
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require './LabStudents/views/main_window'
4
+ require './LabStudents/repositories/student_repository'
5
+ require './LabStudents/repositories/adapters/db_source_adapter'
6
+ require './LabStudents/repositories/containers/data_list_student_short'
7
+ require './LabStudents/views/student_input_form'
8
+ require './LabStudents/controllers/student_input_form/student_input_form_controller_create'
9
+ require './LabStudents/controllers/student_input_form/student_input_form_controller_edit'
10
+ require './LabStudents/util/logger_holder'
11
+ require 'win32api'
12
+
13
+ ##
14
+ # Контроллер для вкладки со списком студентов
15
+
16
+ class TabStudentsController
17
+ def initialize(view)
18
+ LoggerHolder.instance.debug('TabStudentsController: init start')
19
+ @view = view
20
+ @data_list = DataListStudentShort.new([])
21
+ @data_list.add_listener(@view)
22
+ LoggerHolder.instance.debug('TabStudentsController: init done')
23
+ end
24
+
25
+ ##
26
+ # Вызывается из view после ее создания
27
+
28
+ def on_view_created
29
+ begin
30
+ @student_rep = StudentRepository.new(DBSourceAdapter.new)
31
+ LoggerHolder.instance.debug('TabStudentsController: created student repository')
32
+ rescue Mysql2::Error::ConnectionError => e
33
+ on_db_conn_error(e)
34
+ end
35
+ end
36
+
37
+
38
+ ##
39
+ # Показать модальное окно с добавлением студента
40
+
41
+ def show_modal_add
42
+ LoggerHolder.instance.debug('TabStudentsController: showing modal (add)')
43
+ controller = StudentInputFormControllerCreate.new(self)
44
+ view = StudentInputForm.new(controller)
45
+ controller.set_view(view)
46
+ view.create.show
47
+ end
48
+
49
+ ##
50
+ # Показать модальное окно с изменением выделенного студента
51
+
52
+ def show_modal_edit(current_page, per_page, selected_row)
53
+ LoggerHolder.instance.debug('TabStudentsController: showing modal (edit)')
54
+ student_num = (current_page - 1) * per_page + selected_row
55
+ @data_list.select_element(student_num)
56
+ student_id = @data_list.selected_id
57
+ controller = StudentInputFormControllerEdit.new(self, student_id)
58
+ view = StudentInputForm.new(controller)
59
+ controller.set_view(view)
60
+ view.create.show
61
+ end
62
+
63
+ ##
64
+ # Удалить выбранного студента
65
+
66
+ def delete_selected(current_page, per_page, selected_row)
67
+ begin
68
+ LoggerHolder.instance.debug('TabStudentsController: deleting selected student')
69
+ student_num = (current_page - 1) * per_page + selected_row
70
+ @data_list.select_element(student_num)
71
+ student_id = @data_list.selected_id
72
+ @student_rep.remove_student(student_id)
73
+ rescue Mysql2::Error::ConnectionError => e
74
+ on_db_conn_error(e)
75
+ end
76
+ end
77
+
78
+ ##
79
+ # Обновить данные в таблице студентов
80
+
81
+ def refresh_data(page, per_page)
82
+ begin
83
+ LoggerHolder.instance.debug('TabStudentsController: refreshing data...')
84
+ @data_list = @student_rep.paginated_short_students(page, per_page, @data_list)
85
+ @view.update_student_count(@student_rep.student_count)
86
+ rescue Mysql2::Error::ConnectionError => e
87
+ on_db_conn_error(e)
88
+ end
89
+ end
90
+
91
+ private
92
+
93
+ ##
94
+ # Обработчик ошибки подключения к БД
95
+
96
+ def on_db_conn_error(error)
97
+ LoggerHolder.instance.error('TabStudentsController: DB connection error:')
98
+ LoggerHolder.instance.error(error.message)
99
+ api = Win32API.new('user32', 'MessageBox', ['L', 'P', 'P', 'L'], 'I')
100
+ api.call(0, "No connection to DB", "Error", 0)
101
+ # TODO: Возможность переключения на JSON помимо exit
102
+ exit(false)
103
+ end
104
+ end
@@ -0,0 +1,5 @@
1
+ host: 'localhost'
2
+ port: 3306
3
+ username: 'root'
4
+ password: 'root'
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,6 @@
1
+ insert into student(last_name, first_name, father_name, phone, telegram, email, git) values
2
+ ('Тимофеев', 'Иван', 'Георгиевич', '79517532585', NULL, 'timka@mail.ru', NULL),
3
+ ('Кот', 'Александр', 'Дмитриевич', NULL, 'prettykitty', 'kot@bk.ru', 'kotkotkot'),
4
+ ('Симонов', 'Аркадий', 'Олегович', '79998881487', 'simark', 'arksim@gmail.com', NULL),
5
+ ('Балбесов', 'Никита', 'Никитович', '79180005577', 'balnik', NULL, 'nikitos_b'),
6
+ ('Титов', 'Артур', 'Николаевич', '79990805051', 'narot', 'aptyp@narod.ru', 'bot_waasabi');
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative 'student_base'
5
+
6
+ ##
7
+ # Модель студента
8
+
9
+ class Student < StudentBase
10
+ public_class_method :new
11
+
12
+ ##
13
+ # Конструктор из Hash. Ключи являются символами
14
+ def self.from_hash(hash)
15
+ hash = hash.dup
16
+ raise ArgumentError, 'Fields required: fist_name, last_name, father_name' unless hash.key?(:first_name) && hash.key?(:last_name) && hash.key?(:father_name)
17
+
18
+ first_name = hash.delete(:first_name)
19
+ last_name = hash.delete(:last_name)
20
+ father_name = hash.delete(:father_name)
21
+
22
+ Student.new(last_name, first_name, father_name, **hash)
23
+ end
24
+
25
+ ##
26
+ # Конструктор из JSON строки
27
+
28
+ def self.from_json_str(str)
29
+ params = JSON.parse(str, { symbolize_names: true })
30
+ from_hash(params)
31
+ end
32
+
33
+ public :phone, :telegram, :email, 'id=', 'phone=', 'telegram=', 'email=', 'git='
34
+
35
+ attr_reader :last_name, :first_name, :father_name
36
+
37
+ ##
38
+ # Стандартный конструктор. Принимает: Фамилия, Имя, Отчество, а также именованные параметры для предка
39
+ def initialize(last_name, first_name, father_name, **options)
40
+ self.last_name = last_name
41
+ self.first_name = first_name
42
+ self.father_name = father_name
43
+ super(**options)
44
+ end
45
+
46
+ def last_name=(new_last_name)
47
+ raise ArgumentError, "Invalid argument: last_name=#{new_last_name}" unless Student.valid_name?(new_last_name)
48
+
49
+ @last_name = new_last_name
50
+ end
51
+
52
+ def first_name=(new_first_name)
53
+ raise ArgumentError, "Invalid argument: first_name=#{new_first_name}" unless Student.valid_name?(new_first_name)
54
+
55
+ @first_name = new_first_name
56
+ end
57
+
58
+ def father_name=(new_father_name)
59
+ raise ArgumentError, "Invalid argument: father_name=#{new_father_name}" unless Student.valid_name?(new_father_name)
60
+
61
+ @father_name = new_father_name
62
+ end
63
+
64
+ ##
65
+ # Сеттер для массовой установки контактов
66
+
67
+ def set_contacts(phone: nil, telegram: nil, email: nil)
68
+ self.phone = phone if phone
69
+ self.telegram = telegram if telegram
70
+ self.email = email if email
71
+ end
72
+
73
+ ##
74
+ # Вернуть фамилию и инициалы в виде строки "Фамилия И. О."
75
+
76
+ def last_name_and_initials
77
+ "#{last_name} #{first_name[0]}. #{father_name[0]}."
78
+ end
79
+
80
+ ##
81
+ # Краткая информация о пользователе в виде JSON строки.
82
+ # Поля:
83
+ # last_name_and_initials - Фамилия и инициалы в виде "Фамилия И. О."
84
+ # contact - Приоритетный доступный контакт в виде хеша (StudentBase#short_contact)
85
+ # git - Имя пользователя на гите
86
+
87
+ def short_info
88
+ info = {}
89
+ info[:last_name_and_initials] = last_name_and_initials
90
+ info[:contact] = short_contact
91
+ info[:git] = git
92
+ JSON.generate(info)
93
+ end
94
+
95
+ ##
96
+ # Преобразование студента в строку
97
+
98
+ def to_s
99
+ result = "#{last_name} #{first_name} #{father_name}"
100
+ %i[id phone telegram email git].each do |attr|
101
+ attr_val = send(attr)
102
+ result += ", #{attr}=#{attr_val}" unless attr_val.nil?
103
+ end
104
+ result
105
+ end
106
+
107
+ ##
108
+ # Преобразование студента в хеш. Поля являются ключами
109
+
110
+ def to_hash
111
+ attrs = {}
112
+ %i[last_name first_name father_name id phone telegram email git].each do |attr|
113
+ attr_val = send(attr)
114
+ attrs[attr] = attr_val unless attr_val.nil?
115
+ end
116
+ attrs
117
+ end
118
+
119
+ ##
120
+ # Преобразование студента в JSON строку.
121
+
122
+ def to_json_str
123
+ JSON.generate(to_hash)
124
+ end
125
+ end