summaryrefslogtreecommitdiffstats
path: root/lib/contact.rb
blob: cb9a6e9eb2c2ac80d662584e04bf5a0244e02088 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Contact
  attr_reader :name, :street, :postcode, :city, :phone, :email

  def initialize(params = nil)
    if params
      @name = params['name']
      @street = params['street']
      @postcode = params['postcode']
      @city = params['city']
      @phone = params['phone']
      @email = params['email']
    end
  end

  def addr
    "#{@street}, #{@postcode} #{@city}"
  end

  def valid?
    validate!
    @errors.length == 0
  end

  def validate!
    @errors = []
    if @name.nil? || @name.strip.empty?
      @errors << "Du må oppgi en kontaktperson"
    end

    unless valid_postcode
      @errors << "Du må oppgi et gyldig postnr."
    end

    if @city.nil? || @city.strip.empty?
      @errors << "Du må oppgi poststed."
    end

    if @phone.nil? || @phone.strip.empty?
      @errors << "Du må oppgi et telefonnummer"
    end

    if @email.nil? || @email.strip.empty?
      @errors << "Du må oppgi en epostadresse"
    end

    @errors
  end

  private

  def valid_postcode
    @postcode && @postcode =~ /^\d{4}$/
  end
end