refactor: simplify Person class initialization and validation logic

lab2
Artem-Darius Weber 4 weeks ago
parent 5550b9563b
commit 5cd9be99e3

@ -1,62 +1,42 @@
require_relative 'contact'
class Person class Person
attr_accessor :id, :git attr_accessor :id, :git
attr_reader :contact
def initialize(args = {}) def initialize(id:, git:, contact: Contact.new)
@id = args[:id] || nil @id = id
@git = args[:git] @git = git
@contact = contact
raise ArgumentError, "Git link is required" unless git_present?
raise ArgumentError, "At least one contact (phone, telegram, or email) is required" unless contact_present?
end
def set_contacts(phone: nil, telegram: nil, email: nil)
@phone = phone
raise ArgumentError, "Invalid phone number format: #{@phone}" if @phone && !self.class.valid_phone_number?(@phone)
@telegram = telegram
raise ArgumentError, "Invalid telegram format: #{@telegram}" if @telegram && !self.class.valid_telegram?(@telegram)
@email = email validate_person
raise ArgumentError, "Invalid email format: #{@email}" if @email && !self.class.valid_email?(@email)
end end
def self.valid_phone_number?(phone) def git_present?
phone.match?(/\A\+?[0-9]{10,15}\z/) !@git.nil? && !@git.empty?
end
def self.valid_name?(name)
name.match?(/\A[А-Яа-яЁёA-Za-z\-]+\z/)
end end
def self.valid_telegram?(telegram) def contact_present?
telegram.nil? || telegram.match?(/\A@[A-Za-z0-9_]{5,32}\z/) @contact.present?
end end
def self.valid_email?(email) def contact_info
email.nil? || email.match?(/\A[^@\s]+@[^@\s]+\.[^@\s]+\z/) @contact.info
end end
def self.valid_git?(git) def self.valid_git?(git)
git.nil? || git.match?(/\Ahttps:\/\/github\.com\/[A-Za-z0-9_\-]+\z/) /\Ahttps:\/\/github\.com\/[A-Za-z0-9_\-]+\z/.match?(git)
end
def git_present?
!@git.nil? && !@git.empty?
end end
def contact_present? def self.valid_id?(id)
!(@phone.nil? || @phone.empty?) || !(@telegram.nil? || @telegram.empty?) || !(@email.nil? || @email.empty?) id.is_a?(String) && !id.strip.empty?
end
def contact_info
return "Phone: #{@phone}" if @phone
return "Telegram: #{@telegram}" if @telegram
return "Email: #{@email}" if @email
'No contact available'
end end
private private
attr_reader :phone, :telegram, :email def validate_person
attr_writer :phone, :telegram, :email raise ArgumentError, 'ID is required and must be a non-empty string' unless self.class.valid_id?(@id)
raise ArgumentError, 'Git link is required' unless git_present?
raise ArgumentError, 'Invalid Git link format' unless self.class.valid_git?(@git)
end
end end
Loading…
Cancel
Save