feat: Add contact validation and secure modification for Student class

- Implemented `set_contacts` method to safely set phone, telegram, and email fields.
- Made contact fields (`phone`, `telegram`, `email`) private and accessible only through `set_contacts`.
- Added validation within `set_contacts` to ensure contact fields are correctly formatted.
- Modified the `initialize` method to utilize `set_contacts` for setting contact values during object creation.
- Added checks in the `validate` method to ensure Git presence and at least one contact method.
- Updated test cases in `main.rb` to demonstrate correct and incorrect uses of contact modifications.
- Ensured that contact fields cannot be modified directly, maintaining data integrity.
pull/4/head lab2.1
Artem-Darius Weber 4 months ago
parent c1ca0ea845
commit 1407d3e6fd

@ -6,22 +6,28 @@ begin
name: 'Артем-Дариус',
patronymic: 'Вебер',
id: 1,
git: 'https://git.djft.ru'
)
student1.set_contacts(
phone: '+79891242223',
telegram: '@alstroemeria22',
email: 'no-replay@djft.ru',
git: 'https://git.djft.ru'
email: 'no-replay@djft.ru'
)
student2 = Student.new(
surname: 'nil',
surname: 'Норакет',
name: 'Норакет',
patronymic: 'nil'
patronymic: 'Фамилия'
)
student2.set_contacts(
phone: '+70000000000'
)
puts student1
puts '-' * 40
puts student2
rescue ArgumentError => e
puts "Err.: #{e.message}"
puts "Ошибка: #{e.message}"
end

@ -1,5 +1,5 @@
class Student
attr_accessor :id, :surname, :name, :patronymic, :phone, :telegram, :email, :git
attr_accessor :id, :surname, :name, :patronymic, :git
def self.valid_phone_number?(phone)
phone.match?(/\A\+?[0-9]{10,15}\z/)
@ -33,16 +33,11 @@ class Student
@id = args[:id] || nil
@phone = args[:phone]
if @phone && !Student.valid_phone_number?(@phone)
raise ArgumentError, "Invalid phone number format: #{@phone}"
end
@telegram = args[:telegram]
raise ArgumentError, "Invalid telegram format: #{@telegram}" unless Student.valid_telegram?(@telegram)
@email = args[:email]
raise ArgumentError, "Invalid email format: #{@email}" unless Student.valid_email?(@email)
set_contacts(
phone: args[:phone],
telegram: args[:telegram],
email: args[:email]
)
@git = args[:git]
raise ArgumentError, "Invalid git format: #{@git}" unless Student.valid_git?(@git)
@ -50,6 +45,17 @@ class Student
validate
end
def set_contacts(phone: nil, telegram: nil, email: nil)
@phone = phone
raise ArgumentError, "Invalid phone number format: #{@phone}" if @phone && !Student.valid_phone_number?(@phone)
@telegram = telegram
raise ArgumentError, "Invalid telegram format: #{@telegram}" if @telegram && !Student.valid_telegram?(@telegram)
@email = email
raise ArgumentError, "Invalid email format: #{@email}" if @email && !Student.valid_email?(@email)
end
def git_present?
!@git.nil? && !@git.empty?
end
@ -71,4 +77,10 @@ class Student
"Email: #{@email || 'N/A'}\n" \
"Git: #{@git || 'N/A'}"
end
private
attr_reader :phone, :telegram, :email
attr_writer :phone, :telegram, :email
end
Loading…
Cancel
Save