# SPDX-FileCopyrightText: 2020 IN COMMON Collective # # 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, :meta, :version # validates_associated :agent validates :name, presence: true, length: { in: 3..64 } validates :email, format: { with: 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 }, allow_blank: 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 format('%3.7f', lon: feature['geometry']['coordinates'][0]).to_f end def longitude=(value) feature['geometry']['coordinates'][0] = format('%3.7f', lon: value.to_f).to_f end # You can use, e.g.: res.latitude = 0.123 def latitude format('%2.7f', lat: feature['geometry']['coordinates'][1]).to_f end def latitude=(value) feature['geometry']['coordinates'][1] = format('%2.7f', lat: value.to_f).to_f end # Properties [:name, :summary, :description, :email, :source, :address, :postal_code, :city, :phone_number, :website, :entry_number].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 # Poor man's GeoJSON output def to_geojson out = feature.dup # Convert original Dewey IDs with local Section IDs out['properties']['categories'] = Section.where(dewey_id: out['properties']['categories']).pluck(:id) # Add IN COMMON Resource UUID property out['properties']['uuid'] = uuid # Add IN COMMON Agent UUID property out['version'] = { agent: agent.uuid, resource: uuid, revision: 1 } out end end