module G5Updatable class Location < ActiveRecord::Base include G5Updatable::FirstClassProperties include G5Updatable::UrnAsParameter include BelongsToClient has_many :hub_amenities_locations, foreign_key: :g5_updatable_location_id, dependent: :destroy has_many :hub_amenities, through: :hub_amenities_locations validates :uid, :urn, :client_uid, :client_urn, presence: true validates :urn, uniqueness: true scope :by_client_uid, -> (client_uid) { where(client_uid: client_uid) } scope :by_client_urn, -> (client_urn) { where(client_urn: client_urn) } scope :by_postal_code, -> (postal_code) { by_property('postal_code', postal_code) } scope :by_city, -> (city) { by_property('city', city) } scope :by_state, -> (state) { by_property('state', state) } scope :in_status, -> (status) { where("g5_updatable_locations.properties ->> 'status' IN (?)", status) } scope :by_neighborhood, -> (neighborhood) { where("g5_updatable_locations.properties ->> 'neighborhood' = :neighborhood OR g5_updatable_locations.properties ->> 'neighborhood_2' = :neighborhood", neighborhood: neighborhood) } scope :by_property, -> (property_name, value) { where("g5_updatable_locations.properties ->> '#{property_name}' = :#{property_name}", property_name.to_sym => value) } scope :by_urn, -> (urn) { where(urn: urn) } scope :max_updated_at, -> { maximum(:updated_at) } scope :by_amenity_names, -> (*amenity_names) { # there must be a match for every amenity name (AND not OR) results = all [amenity_names].flatten.each do |amenity_name| results = results.where('g5_updatable_locations.flat_amenity_names LIKE :amenity_names', amenity_names: "%#{amenity_names_to_tokenized_string(amenity_name)}%") end results } before_validation :set_client_urn, :set_client_uid def refresh_flat_amenity_names! update_attributes(flat_amenity_names: self.class.amenity_names_to_tokenized_string(hub_amenities.collect(&:name))) end def amenity_names_array=(names_array) self.flat_amenity_names = self.class.amenity_names_to_tokenized_string names_array end FLAT_DELIM = '|' def self.amenity_names_to_tokenized_string(names_array) return if names_array.blank? "#{FLAT_DELIM}#{[names_array].flatten.compact.sort.join(FLAT_DELIM)}#{FLAT_DELIM}" end def display_name return nil unless properties return properties['internal_branded_name'] if properties['internal_branded_name'].present? name end def neighborhoods [properties['neighborhood'], properties['neighborhood_2']].select(&:present?) end def live? status?("Live") end def no_deploy? status?("No Deploy") end def pending? status?("Pending") end def deleted? status?("Deleted") end def suspended? status?("Suspended") end def status?(status) return false unless properties match = properties['status'].to_s.strip =~ /#{status.to_s.strip}/i !!match end def set_client_urn self.client_urn ||= self.client_uid.split('/').last if self.client_uid end def set_client_uid self.client_uid||= self.client.try(:uid) end end end