diff --git a/lab2/contact.rb b/lab2/contact.rb index ec032c0..e20c619 100644 --- a/lab2/contact.rb +++ b/lab2/contact.rb @@ -1,34 +1,19 @@ class Contact attr_reader :phone, :telegram, :email - def initialize(phone: nil, telegram: nil, email: nil) + def initialize(args = {}) + phone = args[:phone] + telegram = args[:telegram] + email = args[:email] + + raise ArgumentError, "Недопустимый номер телефона: #{phone}" if phone && !valid_phone_number?(phone) + raise ArgumentError, "Некорректный Telegram: #{telegram}" if telegram && !valid_telegram?(telegram) + raise ArgumentError, "Некорректный email: #{email}" if email && !valid_email?(email) + raise ArgumentError, "Необходимо указать хотя бы один контакт (телефон, Telegram или email)" unless phone || telegram || email + @phone = phone @telegram = telegram @email = email - validate_contacts - end - - def valid_phone_number? - return true if @phone.nil? - - # Разрешить от 9 до 15 цифр - /\A\+?[0-9]{9,15}\z/.match?(@phone) - end - - def valid_telegram? - return true if @telegram.nil? - - /\A@[A-Za-z0-9_]{5,32}\z/.match?(@telegram) - end - - def valid_email? - return true if @email.nil? - - /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/.match?(@email) - end - - def present? - @phone || @telegram || @email end def info @@ -41,19 +26,23 @@ class Contact private - def validate_contacts - if !present? - raise ArgumentError, 'At least one contact (phone, telegram, or email) is required' - end + def valid_phone_number?(phone) + /\A\+?[0-9]{9,15}\z/.match?(phone) + end - raise ArgumentError, "Invalid phone number format: #{@phone}" if @phone && !valid_phone_number? - raise ArgumentError, "Invalid telegram format: #{@telegram}" if @telegram && !valid_telegram? - raise ArgumentError, "Invalid email format: #{@email}" if @email && !valid_email? + def valid_telegram?(telegram) + /\A@[A-Za-z0-9_]{5,32}\z/.match?(telegram) end + def valid_email?(email) + /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/.match?(email) + end + + public + def self.new_from_info(info_string) info_string = info_string.sub(/^Contact: /, '').strip - + case info_string when /\APhone: (.+)\z/i new(phone: Regexp.last_match(1).strip) @@ -62,7 +51,7 @@ class Contact when /\AEmail: (.+)\z/i new(email: Regexp.last_match(1).strip) else - raise ArgumentError, "Invalid contact info format: #{info_string}" + raise ArgumentError, "Некорректный формат строки контакта: #{info_string}" end end end