aboutsummaryrefslogtreecommitdiff
path: root/app/models/resource.rb
blob: 8df106c39b859c05fe85b74dd9687e26fe028067 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# SPDX-FileCopyrightText: 2020 IN COMMON Collective <collective@incommon.cc>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

require_dependency 'phony_rails'

class Resource < ApplicationRecord
  # Universally Unique Identifier :uuid
  include UUIDParameter

  belongs_to :agent
  has_many :classifications
  has_many :sections, through: :classifications

  store_accessor :feature, :geometry, :properties

  validates_associated :agent

  validates :name,
            presence: true,
            length: { in: 3..64 }

  validates :email,
            with: { format: URI::MailTo::EMAIL_REGEXP },
            allow_blank: true

  validates :source,
            inclusion: { in: Agent.pluck(:name) }

  # TODO: Address,Postal Code,City validation

  phony_normalize :phone_number, default_country_code: 'BE', normalize_when_valid: true
  validates :phone_number,
            phony_plausible: { ignore_record_country_code: true, ignore_record_country_number: true }

  # Depends on validate_url Gem
  validates :website,
            url: { allow_blank: true }

  # Accessors for feature['geometry']
  def geo_type
    self.feature['geometry']['type']
  end

  # You can use, e.g.: res.longitude = 0.123
  def longitude
    feature['geometry']['coordinates'][0]
  end
  def longitude=(value)
    feature['geometry']['coordinates'][0] = value
  end
  # You can use, e.g.: res.latitude = 0.123
  def latitude
    feature['geometry']['coordinates'][1]
  end
  def latitude=(value)
    feature['geometry']['coordinates'][1] = value
  end

  # Properties

  [:name, :summary, :description, :email, :source, :address, :postal_code, :city, :phone_number, :website].each do |prop|
    # Define a reader
    define_method prop do
      properties[prop.to_s]
    end
    define_method :"#{prop}=" do |v|
      feature['properties'][prop.to_s] = v
    end
  end
end