Class: TaxonNameClassification
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- TaxonNameClassification
- Includes:
- Housekeeping, Shared::BatchByFilterScope, Shared::Citations, Shared::IsData, Shared::Notes, SoftValidation
- Defined in:
- app/models/taxon_name_classification.rb
Overview
Defined Under Namespace
Classes: Icn, Icnp, Icvcn, Iczn, Latinized
Constant Summary
Constants included from SoftValidation
SoftValidation::ANCESTORS_WITH_SOFT_VALIDATIONS
Instance Attribute Summary collapse
-
#project_id ⇒ Integer
the project ID.
-
#taxon_name_id ⇒ Integer
The id of the TaxonName being classified.
-
#type ⇒ String
The type of classifiction (Rails STI).
Class Method Summary collapse
- .annotates? ⇒ Boolean
-
.applicable_ranks ⇒ Array of Strings of NomenclaturalRank names
nomenclatural ranks to which this class is applicable, that is, only TaxonNames of these NomenclaturalRanks may be classified as this class.
- .assignable ⇒ Object
-
.code_applicability_end_year ⇒ Integer
the last year of applicability for this class, defaults to 9999.
-
.code_applicability_start_year ⇒ Integer
the minimum year of applicability for this class, defaults to 1.
-
.collect_descendants_and_itself_to_s(*classes) ⇒ Object
!! using this strongly suggests something can be optimized, meomized etc.
-
.collect_descendants_to_s(*classes) ⇒ Object
!! using this strongly suggests something can be optimized, meomized etc.
- .collect_to_s(*args) ⇒ Object
-
.destroy_classifications_for_batch(classifications:, query:, batch_response:) ⇒ Object
Destroys
classificationsbelonging to taxon names inquery. -
.disjoint_taxon_name_classes ⇒ Array of Strings of TaxonNameClassification names
the disjoint (inapplicable) TaxonNameClassifications for this class, that is, TaxonNames classified as this class can not be additionally classified under these classes.
- .dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) ⇒ Object
-
.gbif_status ⇒ String?
If applicable, a DWC gbif status for this class.
- .label ⇒ Object
- .nomen_uri ⇒ Object
-
.parent ⇒ Object
Class this method calls Module#module_parent.
-
.possible_genus_endings ⇒ Array of Strings
the possible suffixes for a TaxonName name (genus) classified as this class, for example see Latinized::Gender::Masculine.
-
.possible_species_endings ⇒ Array of Strings
The possible suffixes for a TaxonName name (species) classified as this class, for example see Latinized::Gender::Masculine used to validate gender agreement of species name with a genus.
- .process_batch_by_filter_scope(batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false) ⇒ BatchResponse
-
.questionable_species_endings ⇒ Array of Strings
The questionable suffixes for a TaxonName name classified as this class, for example see Latinized::Gender::Masculine.
Instance Method Summary collapse
- #annotated_object ⇒ Object
-
#classification_label ⇒ String
A humanized class name, with code appended to differentiate !! explored idea of LABEL in individual subclasses, use this if this doesn't work this is helper-esqe, but also useful in validation, so here for now.
-
#nomen_id ⇒ String
The NOMEN id for this classification.
- #nomenclature_code ⇒ Object
- #nomenclature_code_matches ⇒ Object private
- #set_cached ⇒ Object
-
#set_cached_names_for_taxon_names ⇒ Object
TODO: move these to individual classes?! Starting to move to individual classes Gender is sone.
- #sv_fix_proper_classification ⇒ Object
- #sv_not_specific_classes ⇒ Object
- #sv_proper_classification ⇒ Object
- #sv_proper_year ⇒ Object
- #sv_validate_disjoint_classes ⇒ Object
- #type_class ⇒ Object
- #type_class=(value) ⇒ Object
-
#type_name ⇒ String
The class name, "validated" against the known list of names.
-
#validate_taxon_name_classification ⇒ Object
private
TODO: unnecessary! Type handling will raise here.
- #validate_uniqueness_of_latinized ⇒ Object
Methods included from SoftValidation
#clear_soft_validations, #fix_for, #fix_soft_validations, #soft_fixed?, #soft_valid?, #soft_validate, #soft_validated?, #soft_validations, #soft_validators
Methods included from Shared::IsData
#errors_excepting, #full_error_messages_excepting, #identical, #is_community?, #is_in_use?, #similar
Methods included from Shared::Notes
#concatenated_notes_string, #reject_notes
Methods included from Shared::Citations
#cited?, #mark_citations_for_destruction, #nomenclature_date, #origin_citation_source_id, #reject_citations, #requires_citation?, #sources_by_topic_id
Methods included from Housekeeping
#has_polymorphic_relationship?
Methods inherited from ApplicationRecord
Instance Attribute Details
#project_id ⇒ Integer
the project ID
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'app/models/taxon_name_classification.rb', line 18 class TaxonNameClassification < ApplicationRecord include Housekeeping include Shared::BatchByFilterScope include Shared::Citations include Shared::Notes include Shared::IsData include SoftValidation belongs_to :taxon_name, inverse_of: :taxon_name_classifications before_validation :validate_taxon_name_classification before_validation :validate_uniqueness_of_latinized after_commit :set_cached validates_presence_of :taxon_name validates_presence_of :type validates_uniqueness_of :taxon_name_id, scope: [:type, :project_id] validate :nomenclature_code_matches scope :where_taxon_name, -> (taxon_name) {where(taxon_name_id: taxon_name)} scope :with_type_string, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}" ) } scope :with_type_base, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}%" ) } scope :with_type_array, -> (base_array) {where('taxon_name_classifications.type IN (?)', base_array ) } scope :with_type_contains, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "%#{base_string}%" ) } soft_validate(:sv_proper_classification, set: :proper_classification, fix: :sv_fix_proper_classification, name: 'Applicable status', description: 'Check the status applicability.' ) soft_validate(:sv_proper_year, set: :proper_classification, name: 'Applicable protonym year', description: 'Check that the status is compatible with the year of publication of taxon.' ) soft_validate(:sv_validate_disjoint_classes, set: :validate_disjoint_classes, name: 'Conflicting status', description: 'Taxon has two conflicting statuses' ) soft_validate(:sv_not_specific_classes, set: :not_specific_classes, name: 'Not specific status', description: 'More specific statuses are preffered, for example: "Nomen nudum, no description" is better than "Nomen nudum".' ) def nomenclature_code return :iczn if type.match(/::Iczn/) return :icnp if type.match(/::Icnp/) return :icvcn if type.match(/::Icvcn/) return :icn if type.match(/::Icn/) return nil end def self.label name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish end # @return class # this method calls Module#module_parent def self.parent self.module_parent end # @return [String] # the class name, "validated" against the known list of names def type_name r = self.type.to_s ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r : nil end def type_class=(value) write_attribute(:type, value.to_s) end def type_class r = read_attribute(:type).to_s r = ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r.safe_constantize : nil end # @return [String] # a humanized class name, with code appended to differentiate # !! explored idea of LABEL in individual subclasses, use this if this doesn't work # this is helper-esqe, but also useful in validation, so here for now def classification_label return nil if type_name.nil? type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish #+ #(nomenclature_code ? " [#{nomenclature_code}]" : '') end # @return [String] # the NOMEN id for this classification def nomen_id self.class::NOMEN_URI.split('/').last end # Attributes can be overridden in descendants # @return [Integer] # the minimum year of applicability for this class, defaults to 1 def self.code_applicability_start_year 1 end # @return [Integer] # the last year of applicability for this class, defaults to 9999 def self.code_applicability_end_year 9999 end # @return [Array of Strings of NomenclaturalRank names] # nomenclatural ranks to which this class is applicable, that is, only {TaxonName}s of these {NomenclaturalRank}s may be classified as this class def self.applicable_ranks [] end # @return [Array of Strings of TaxonNameClassification names] # the disjoint (inapplicable) {TaxonNameClassification}s for this class, that is, {TaxonName}s classified as this class can not be additionally classified under these classes def self.disjoint_taxon_name_classes [] end # @return [String, nil] # if applicable, a DWC gbif status for this class def self.gbif_status nil end def self.assignable false end #def self.common # false #end # @todo Perhaps not inherit these three meaxonNameClassificationsHelper::descendants_collection( TaxonNameClassification::Latinized )thods? # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (species) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} # used to validate gender agreement of species name with a genus def self.possible_species_endings [] end # @return [Array of Strings] # the questionable suffixes for a {TaxonName} name classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.questionable_species_endings [] end # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (genus) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.possible_genus_endings [] end def self.nomen_uri const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil end def set_cached set_cached_names_for_taxon_names end # TODO: move these to individual classes?! # Starting to move to individual classes # Gender is sone def set_cached_names_for_taxon_names t = taxon_name return if t.destroyed? begin TaxonName.transaction_with_retry do if type_name =~ /(Fossil|Hybrid|Candidatus)/ # Break these out, they don't all apply to the same codes n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) elsif type_name =~ /Latinized::PartOfSpeech/ n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) TaxonNameRelationship::OriginalCombination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_cached_original_combinations end TaxonNameRelationship::Combination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_column(:verbatim_name, t1.cached) if t1.verbatim_name.nil? n = t1.get_full_name t1.update_columns( cached: n, cached_html: t1.get_full_name_html(n) ) end elsif type_name =~ /Latinized::Gender/ # Handled in subclasses raise elsif TAXON_NAME_CLASS_NAMES_VALID.include?(type_name) vn = t.get_valid_taxon_name vn.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: !vn.unavailable_or_invalid?) # Do not change! vn.list_of_invalid_taxon_names.each do |s| s.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: false) s.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end end t.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end else t.update_columns(cached_is_valid: false) end if TAXON_NAME_CLASS_NAMES_UNAVAILABLE.include?( type_name ) t.update_columns( cached_is_available: false ) end end rescue ActiveRecord::RecordInvalid false end true end def validate_uniqueness_of_latinized true # moved to subclasses end def sv_proper_classification if TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type) # self.type_class is a Class if not self.type_class.applicable_ranks.include?(self.taxon_name.rank_string) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} at the rank of #{self.taxon_name.rank_class.rank_name}", success_message: 'The status was deleted', failure_message: 'Fail to delete the status') end end end def sv_fix_proper_classification begin TaxonNameClassification.transaction do self.destroy end return true rescue return false end end def sv_proper_year y = self.taxon_name.year_of_publication if !y.nil? && (y > self.type_class.code_applicability_end_year || y < self.type_class.code_applicability_start_year) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} published in the year #{y}") end end def sv_validate_disjoint_classes classifications = TaxonNameClassification.where_taxon_name(self.taxon_name).not_self(self) classifications.each do |i| soft_validations.add(:type, "The status '#{self.classification_label}' conflicting with another status: '#{i.classification_label}'") if self.type_class.disjoint_taxon_name_classes.include?(i.type_name) end end def sv_not_specific_classes true # moved to subclasses end def self.annotates? true end def annotated_object taxon_name end # @param batch_response [BatchResponse] # @param query [ActiveRecord::Relation] TaxonName scope from the filter # @param hash_query [Hash] serialized filter params, used to re-run the query in async jobs # @param mode [Symbol, String] :set, :remove_gender (gender); :add_status, :remove_status (arbitrary status) # @param params [Hash] :type required for :set, :add_status, :remove_status; # :citation (optional, :add_status only) a Hash with :source_id (required to attach), :pages, :is_original - # attached to the status whether it was just created or already existed; tolerates (does not duplicate or # error on) a citation with the same source, pages, and is_original already present on that status # @param async [Boolean] # @param project_id [Integer] # @param user_id [Integer] # @param called_from_async [Boolean] prevents re-dispatching when already inside a job # @return [BatchResponse] def self.process_batch_by_filter_scope( batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false ) async = false if called_from_async == true r = batch_response case mode.to_sym when :set # gender gender_type = params[:type] return r unless TAXON_NAME_CLASSIFICATIONS_FOR_GENDER.include?(gender_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end existing_by_taxon_name_id = TaxonNameClassification .with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER) .where(taxon_name: query) .index_by(&:taxon_name_id) query.find_each do |taxon_name| if existing = existing_by_taxon_name_id[taxon_name.id] if existing.type == gender_type # Already the requested gender - skip the update entirely rather # than trigger the expensive after_commit cascade (walks every # descendant taxon name to recompute cached spellings) for # nothing. r.updated.push existing.id elsif existing.update(type: gender_type) r.updated.push existing.id else r.not_updated.push taxon_name.id existing.errors..each { |msg| r.validation_errors[msg] += 1 } end else classification = TaxonNameClassification.create( taxon_name: taxon_name, type: gender_type ) if classification.persisted? r.updated.push classification.id else r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } end end end when :remove_gender if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end destroy_classifications_for_batch( classifications: TaxonNameClassification.with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER), query:, batch_response: r ) when :add_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end citation_params = params[:citation]&.symbolize_keys citation_source_id = citation_params && citation_params[:source_id] citation_source = citation_source_id && Source.find_by(id: citation_source_id) existing_by_taxon_name_id = TaxonNameClassification .where(type: status_type) .where(taxon_name: query) .index_by(&:taxon_name_id) # Disjoint types (e.g. Iczn::Fossil::Ichnotaxon is disjoint with its own # parent Iczn::Fossil) already satisfy this status; skip creating a # conflicting status rather than let the two coexist. disjoint_types = status_type.constantize.disjoint_taxon_name_classes conflicting_taxon_name_ids = if disjoint_types.empty? Set.new else TaxonNameClassification .where(type: disjoint_types) .where(taxon_name: query) .distinct .pluck(:taxon_name_id) .to_set end # Classifications that already carry the exact citation (same # source, pages, and is_original) being requested. This isn't just a # performance nicety: it's what distinguishes an identical repeat # (skipped and reported as updated) from a genuine conflict: same # source and pages but a different is_original (attempted, fails, # and is reported below with a message specific to that case). already_cited_classification_ids = if citation_source_id && existing_by_taxon_name_id.any? Citation.duplicate_citation_object_ids( citation_object_type: 'TaxonNameClassification', citation_object_ids: existing_by_taxon_name_id.values.map(&:id), source_id: citation_source_id, pages: citation_params[:pages], is_original: citation_params[:is_original] ) else Set.new end query.find_each do |taxon_name| if ( !existing_by_taxon_name_id.key?(taxon_name.id) && conflicting_taxon_name_ids.include?(taxon_name.id) ) r.not_updated.push taxon_name.id r.validation_errors['conflicts with an existing disjoint classification'] += 1 next end classification = existing_by_taxon_name_id[taxon_name.id] || TaxonNameClassification.create(taxon_name: taxon_name, type: status_type) unless classification.persisted? r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } next end if citation_source_id && !already_cited_classification_ids.include?(classification.id) citation = classification.citations.create( source: citation_source, pages: citation_params[:pages], is_original: citation_params[:is_original] ) unless citation.persisted? r.not_updated.push taxon_name.id # An exact repeat was already ruled out above, so a source_id # conflict here can only mean a citation with this same source # and pages exists with a different is_original - Citation's # own validation doesn't know or care about is_original, it # only reports the source/pages conflict, so the more specific # wording is built here. The taxon name id is included (rather # than summarized by count, as validation_errors normally are) # since this needs manual review to resolve. if citation.errors[:source_id].any? r.validation_errors["citation already exists with a different 'original' flag for taxon name id #{taxon_name.id} - is_original was not changed"] += 1 else # a second `is_original = true` citation, e.g. citation.errors..each { |msg| r.validation_errors[msg] += 1 } end next end end r.updated.push classification.id end when :remove_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) return r end # Only the exact type selected: not its subclasses (e.g. removing # Iczn::Fossil leaves Iczn::Fossil::Ichnotaxon), and not # disjoint_taxon_name_classes, which is every *conflicting* status. destroy_classifications_for_batch( classifications: TaxonNameClassification.where(type: status_type), query:, batch_response: r ) end r end # Destroys `classifications` belonging to taxon names in `query`. # Iterates every taxon name in the query (not just ones with a matching # classification) so updated/not_updated always account for the full # total_attempted. A taxon name with nothing to remove lands in # not_updated with no validation_errors entry; if a destroy were ever to # fail (nothing currently blocks one) it would also land in not_updated, # but with an error message - that's how the two would be told apart. def self.destroy_classifications_for_batch(classifications:, query:, batch_response:) existing_by_taxon_name_id = classifications .where(taxon_name: query) .includes(:taxon_name) # used by the set_cached callback .group_by(&:taxon_name_id) query.find_each do |taxon_name| found = existing_by_taxon_name_id[taxon_name.id] || [] if found.empty? batch_response.not_updated.push taxon_name.id next end failed = found.reject do |c| c.destroy # destroy is necessary to update cached values c.destroyed? end if failed.empty? batch_response.updated.push nil else # never happens? batch_response.not_updated.push taxon_name.id failed.each { |c| c.errors..each { |msg| batch_response.validation_errors[msg] += 1 } } end end end def self.dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) BatchByFilterScopeJob.perform_later( klass: self.name, hash_query:, mode:, params:, project_id:, user_id: ) end private def nomenclature_code_matches if taxon_name && type && nomenclature_code tn = taxon_name.is_combination? ? taxon_name.protonyms.last : taxon_name nc = tn.rank_class.nomenclatural_code if nomenclature_code != nc taxon_name_code = nc.nil? ? 'no' : "the #{nc}" errors.add(:taxon_name, "#{taxon_name.cached_html} belongs to #{taxon_name_code} nomenclatural code, but the status is from the #{nomenclature_code} nomenclatural code") end end end # TODO: unnecessary! Type handling will raise here def validate_taxon_name_classification errors.add(:type, 'Status not found') if !self.type.nil? and !TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type.to_s) end # @todo move these to a shared library (see NomenclaturalRank too) def self.collect_to_s(*args) args.collect{|arg| arg.to_s} end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_to_s(*classes) ans = [] classes.each do |klass| ans += klass.descendants.collect{|k| k.to_s} end ans end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_and_itself_to_s(*classes) classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes) end # Force loading all descendants as soon as this class is referenced Dir.glob("#{Rails.root}/app/models/taxon_name_classification/**/*.rb") .sort { |a, b| a.split('/').count <=> b.split('/').count } .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') } .map { |p| p.split('/') } .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } } .map { |c| c.join('::') }.map(&:constantize) end |
#taxon_name_id ⇒ Integer
Returns the id of the TaxonName being classified.
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'app/models/taxon_name_classification.rb', line 18 class TaxonNameClassification < ApplicationRecord include Housekeeping include Shared::BatchByFilterScope include Shared::Citations include Shared::Notes include Shared::IsData include SoftValidation belongs_to :taxon_name, inverse_of: :taxon_name_classifications before_validation :validate_taxon_name_classification before_validation :validate_uniqueness_of_latinized after_commit :set_cached validates_presence_of :taxon_name validates_presence_of :type validates_uniqueness_of :taxon_name_id, scope: [:type, :project_id] validate :nomenclature_code_matches scope :where_taxon_name, -> (taxon_name) {where(taxon_name_id: taxon_name)} scope :with_type_string, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}" ) } scope :with_type_base, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}%" ) } scope :with_type_array, -> (base_array) {where('taxon_name_classifications.type IN (?)', base_array ) } scope :with_type_contains, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "%#{base_string}%" ) } soft_validate(:sv_proper_classification, set: :proper_classification, fix: :sv_fix_proper_classification, name: 'Applicable status', description: 'Check the status applicability.' ) soft_validate(:sv_proper_year, set: :proper_classification, name: 'Applicable protonym year', description: 'Check that the status is compatible with the year of publication of taxon.' ) soft_validate(:sv_validate_disjoint_classes, set: :validate_disjoint_classes, name: 'Conflicting status', description: 'Taxon has two conflicting statuses' ) soft_validate(:sv_not_specific_classes, set: :not_specific_classes, name: 'Not specific status', description: 'More specific statuses are preffered, for example: "Nomen nudum, no description" is better than "Nomen nudum".' ) def nomenclature_code return :iczn if type.match(/::Iczn/) return :icnp if type.match(/::Icnp/) return :icvcn if type.match(/::Icvcn/) return :icn if type.match(/::Icn/) return nil end def self.label name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish end # @return class # this method calls Module#module_parent def self.parent self.module_parent end # @return [String] # the class name, "validated" against the known list of names def type_name r = self.type.to_s ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r : nil end def type_class=(value) write_attribute(:type, value.to_s) end def type_class r = read_attribute(:type).to_s r = ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r.safe_constantize : nil end # @return [String] # a humanized class name, with code appended to differentiate # !! explored idea of LABEL in individual subclasses, use this if this doesn't work # this is helper-esqe, but also useful in validation, so here for now def classification_label return nil if type_name.nil? type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish #+ #(nomenclature_code ? " [#{nomenclature_code}]" : '') end # @return [String] # the NOMEN id for this classification def nomen_id self.class::NOMEN_URI.split('/').last end # Attributes can be overridden in descendants # @return [Integer] # the minimum year of applicability for this class, defaults to 1 def self.code_applicability_start_year 1 end # @return [Integer] # the last year of applicability for this class, defaults to 9999 def self.code_applicability_end_year 9999 end # @return [Array of Strings of NomenclaturalRank names] # nomenclatural ranks to which this class is applicable, that is, only {TaxonName}s of these {NomenclaturalRank}s may be classified as this class def self.applicable_ranks [] end # @return [Array of Strings of TaxonNameClassification names] # the disjoint (inapplicable) {TaxonNameClassification}s for this class, that is, {TaxonName}s classified as this class can not be additionally classified under these classes def self.disjoint_taxon_name_classes [] end # @return [String, nil] # if applicable, a DWC gbif status for this class def self.gbif_status nil end def self.assignable false end #def self.common # false #end # @todo Perhaps not inherit these three meaxonNameClassificationsHelper::descendants_collection( TaxonNameClassification::Latinized )thods? # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (species) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} # used to validate gender agreement of species name with a genus def self.possible_species_endings [] end # @return [Array of Strings] # the questionable suffixes for a {TaxonName} name classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.questionable_species_endings [] end # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (genus) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.possible_genus_endings [] end def self.nomen_uri const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil end def set_cached set_cached_names_for_taxon_names end # TODO: move these to individual classes?! # Starting to move to individual classes # Gender is sone def set_cached_names_for_taxon_names t = taxon_name return if t.destroyed? begin TaxonName.transaction_with_retry do if type_name =~ /(Fossil|Hybrid|Candidatus)/ # Break these out, they don't all apply to the same codes n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) elsif type_name =~ /Latinized::PartOfSpeech/ n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) TaxonNameRelationship::OriginalCombination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_cached_original_combinations end TaxonNameRelationship::Combination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_column(:verbatim_name, t1.cached) if t1.verbatim_name.nil? n = t1.get_full_name t1.update_columns( cached: n, cached_html: t1.get_full_name_html(n) ) end elsif type_name =~ /Latinized::Gender/ # Handled in subclasses raise elsif TAXON_NAME_CLASS_NAMES_VALID.include?(type_name) vn = t.get_valid_taxon_name vn.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: !vn.unavailable_or_invalid?) # Do not change! vn.list_of_invalid_taxon_names.each do |s| s.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: false) s.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end end t.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end else t.update_columns(cached_is_valid: false) end if TAXON_NAME_CLASS_NAMES_UNAVAILABLE.include?( type_name ) t.update_columns( cached_is_available: false ) end end rescue ActiveRecord::RecordInvalid false end true end def validate_uniqueness_of_latinized true # moved to subclasses end def sv_proper_classification if TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type) # self.type_class is a Class if not self.type_class.applicable_ranks.include?(self.taxon_name.rank_string) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} at the rank of #{self.taxon_name.rank_class.rank_name}", success_message: 'The status was deleted', failure_message: 'Fail to delete the status') end end end def sv_fix_proper_classification begin TaxonNameClassification.transaction do self.destroy end return true rescue return false end end def sv_proper_year y = self.taxon_name.year_of_publication if !y.nil? && (y > self.type_class.code_applicability_end_year || y < self.type_class.code_applicability_start_year) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} published in the year #{y}") end end def sv_validate_disjoint_classes classifications = TaxonNameClassification.where_taxon_name(self.taxon_name).not_self(self) classifications.each do |i| soft_validations.add(:type, "The status '#{self.classification_label}' conflicting with another status: '#{i.classification_label}'") if self.type_class.disjoint_taxon_name_classes.include?(i.type_name) end end def sv_not_specific_classes true # moved to subclasses end def self.annotates? true end def annotated_object taxon_name end # @param batch_response [BatchResponse] # @param query [ActiveRecord::Relation] TaxonName scope from the filter # @param hash_query [Hash] serialized filter params, used to re-run the query in async jobs # @param mode [Symbol, String] :set, :remove_gender (gender); :add_status, :remove_status (arbitrary status) # @param params [Hash] :type required for :set, :add_status, :remove_status; # :citation (optional, :add_status only) a Hash with :source_id (required to attach), :pages, :is_original - # attached to the status whether it was just created or already existed; tolerates (does not duplicate or # error on) a citation with the same source, pages, and is_original already present on that status # @param async [Boolean] # @param project_id [Integer] # @param user_id [Integer] # @param called_from_async [Boolean] prevents re-dispatching when already inside a job # @return [BatchResponse] def self.process_batch_by_filter_scope( batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false ) async = false if called_from_async == true r = batch_response case mode.to_sym when :set # gender gender_type = params[:type] return r unless TAXON_NAME_CLASSIFICATIONS_FOR_GENDER.include?(gender_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end existing_by_taxon_name_id = TaxonNameClassification .with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER) .where(taxon_name: query) .index_by(&:taxon_name_id) query.find_each do |taxon_name| if existing = existing_by_taxon_name_id[taxon_name.id] if existing.type == gender_type # Already the requested gender - skip the update entirely rather # than trigger the expensive after_commit cascade (walks every # descendant taxon name to recompute cached spellings) for # nothing. r.updated.push existing.id elsif existing.update(type: gender_type) r.updated.push existing.id else r.not_updated.push taxon_name.id existing.errors..each { |msg| r.validation_errors[msg] += 1 } end else classification = TaxonNameClassification.create( taxon_name: taxon_name, type: gender_type ) if classification.persisted? r.updated.push classification.id else r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } end end end when :remove_gender if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end destroy_classifications_for_batch( classifications: TaxonNameClassification.with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER), query:, batch_response: r ) when :add_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end citation_params = params[:citation]&.symbolize_keys citation_source_id = citation_params && citation_params[:source_id] citation_source = citation_source_id && Source.find_by(id: citation_source_id) existing_by_taxon_name_id = TaxonNameClassification .where(type: status_type) .where(taxon_name: query) .index_by(&:taxon_name_id) # Disjoint types (e.g. Iczn::Fossil::Ichnotaxon is disjoint with its own # parent Iczn::Fossil) already satisfy this status; skip creating a # conflicting status rather than let the two coexist. disjoint_types = status_type.constantize.disjoint_taxon_name_classes conflicting_taxon_name_ids = if disjoint_types.empty? Set.new else TaxonNameClassification .where(type: disjoint_types) .where(taxon_name: query) .distinct .pluck(:taxon_name_id) .to_set end # Classifications that already carry the exact citation (same # source, pages, and is_original) being requested. This isn't just a # performance nicety: it's what distinguishes an identical repeat # (skipped and reported as updated) from a genuine conflict: same # source and pages but a different is_original (attempted, fails, # and is reported below with a message specific to that case). already_cited_classification_ids = if citation_source_id && existing_by_taxon_name_id.any? Citation.duplicate_citation_object_ids( citation_object_type: 'TaxonNameClassification', citation_object_ids: existing_by_taxon_name_id.values.map(&:id), source_id: citation_source_id, pages: citation_params[:pages], is_original: citation_params[:is_original] ) else Set.new end query.find_each do |taxon_name| if ( !existing_by_taxon_name_id.key?(taxon_name.id) && conflicting_taxon_name_ids.include?(taxon_name.id) ) r.not_updated.push taxon_name.id r.validation_errors['conflicts with an existing disjoint classification'] += 1 next end classification = existing_by_taxon_name_id[taxon_name.id] || TaxonNameClassification.create(taxon_name: taxon_name, type: status_type) unless classification.persisted? r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } next end if citation_source_id && !already_cited_classification_ids.include?(classification.id) citation = classification.citations.create( source: citation_source, pages: citation_params[:pages], is_original: citation_params[:is_original] ) unless citation.persisted? r.not_updated.push taxon_name.id # An exact repeat was already ruled out above, so a source_id # conflict here can only mean a citation with this same source # and pages exists with a different is_original - Citation's # own validation doesn't know or care about is_original, it # only reports the source/pages conflict, so the more specific # wording is built here. The taxon name id is included (rather # than summarized by count, as validation_errors normally are) # since this needs manual review to resolve. if citation.errors[:source_id].any? r.validation_errors["citation already exists with a different 'original' flag for taxon name id #{taxon_name.id} - is_original was not changed"] += 1 else # a second `is_original = true` citation, e.g. citation.errors..each { |msg| r.validation_errors[msg] += 1 } end next end end r.updated.push classification.id end when :remove_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) return r end # Only the exact type selected: not its subclasses (e.g. removing # Iczn::Fossil leaves Iczn::Fossil::Ichnotaxon), and not # disjoint_taxon_name_classes, which is every *conflicting* status. destroy_classifications_for_batch( classifications: TaxonNameClassification.where(type: status_type), query:, batch_response: r ) end r end # Destroys `classifications` belonging to taxon names in `query`. # Iterates every taxon name in the query (not just ones with a matching # classification) so updated/not_updated always account for the full # total_attempted. A taxon name with nothing to remove lands in # not_updated with no validation_errors entry; if a destroy were ever to # fail (nothing currently blocks one) it would also land in not_updated, # but with an error message - that's how the two would be told apart. def self.destroy_classifications_for_batch(classifications:, query:, batch_response:) existing_by_taxon_name_id = classifications .where(taxon_name: query) .includes(:taxon_name) # used by the set_cached callback .group_by(&:taxon_name_id) query.find_each do |taxon_name| found = existing_by_taxon_name_id[taxon_name.id] || [] if found.empty? batch_response.not_updated.push taxon_name.id next end failed = found.reject do |c| c.destroy # destroy is necessary to update cached values c.destroyed? end if failed.empty? batch_response.updated.push nil else # never happens? batch_response.not_updated.push taxon_name.id failed.each { |c| c.errors..each { |msg| batch_response.validation_errors[msg] += 1 } } end end end def self.dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) BatchByFilterScopeJob.perform_later( klass: self.name, hash_query:, mode:, params:, project_id:, user_id: ) end private def nomenclature_code_matches if taxon_name && type && nomenclature_code tn = taxon_name.is_combination? ? taxon_name.protonyms.last : taxon_name nc = tn.rank_class.nomenclatural_code if nomenclature_code != nc taxon_name_code = nc.nil? ? 'no' : "the #{nc}" errors.add(:taxon_name, "#{taxon_name.cached_html} belongs to #{taxon_name_code} nomenclatural code, but the status is from the #{nomenclature_code} nomenclatural code") end end end # TODO: unnecessary! Type handling will raise here def validate_taxon_name_classification errors.add(:type, 'Status not found') if !self.type.nil? and !TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type.to_s) end # @todo move these to a shared library (see NomenclaturalRank too) def self.collect_to_s(*args) args.collect{|arg| arg.to_s} end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_to_s(*classes) ans = [] classes.each do |klass| ans += klass.descendants.collect{|k| k.to_s} end ans end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_and_itself_to_s(*classes) classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes) end # Force loading all descendants as soon as this class is referenced Dir.glob("#{Rails.root}/app/models/taxon_name_classification/**/*.rb") .sort { |a, b| a.split('/').count <=> b.split('/').count } .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') } .map { |p| p.split('/') } .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } } .map { |c| c.join('::') }.map(&:constantize) end |
#type ⇒ String
Returns the type of classifiction (Rails STI).
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'app/models/taxon_name_classification.rb', line 18 class TaxonNameClassification < ApplicationRecord include Housekeeping include Shared::BatchByFilterScope include Shared::Citations include Shared::Notes include Shared::IsData include SoftValidation belongs_to :taxon_name, inverse_of: :taxon_name_classifications before_validation :validate_taxon_name_classification before_validation :validate_uniqueness_of_latinized after_commit :set_cached validates_presence_of :taxon_name validates_presence_of :type validates_uniqueness_of :taxon_name_id, scope: [:type, :project_id] validate :nomenclature_code_matches scope :where_taxon_name, -> (taxon_name) {where(taxon_name_id: taxon_name)} scope :with_type_string, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}" ) } scope :with_type_base, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "#{base_string}%" ) } scope :with_type_array, -> (base_array) {where('taxon_name_classifications.type IN (?)', base_array ) } scope :with_type_contains, -> (base_string) {where('taxon_name_classifications.type LIKE ?', "%#{base_string}%" ) } soft_validate(:sv_proper_classification, set: :proper_classification, fix: :sv_fix_proper_classification, name: 'Applicable status', description: 'Check the status applicability.' ) soft_validate(:sv_proper_year, set: :proper_classification, name: 'Applicable protonym year', description: 'Check that the status is compatible with the year of publication of taxon.' ) soft_validate(:sv_validate_disjoint_classes, set: :validate_disjoint_classes, name: 'Conflicting status', description: 'Taxon has two conflicting statuses' ) soft_validate(:sv_not_specific_classes, set: :not_specific_classes, name: 'Not specific status', description: 'More specific statuses are preffered, for example: "Nomen nudum, no description" is better than "Nomen nudum".' ) def nomenclature_code return :iczn if type.match(/::Iczn/) return :icnp if type.match(/::Icnp/) return :icvcn if type.match(/::Icvcn/) return :icn if type.match(/::Icn/) return nil end def self.label name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish end # @return class # this method calls Module#module_parent def self.parent self.module_parent end # @return [String] # the class name, "validated" against the known list of names def type_name r = self.type.to_s ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r : nil end def type_class=(value) write_attribute(:type, value.to_s) end def type_class r = read_attribute(:type).to_s r = ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r.safe_constantize : nil end # @return [String] # a humanized class name, with code appended to differentiate # !! explored idea of LABEL in individual subclasses, use this if this doesn't work # this is helper-esqe, but also useful in validation, so here for now def classification_label return nil if type_name.nil? type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish #+ #(nomenclature_code ? " [#{nomenclature_code}]" : '') end # @return [String] # the NOMEN id for this classification def nomen_id self.class::NOMEN_URI.split('/').last end # Attributes can be overridden in descendants # @return [Integer] # the minimum year of applicability for this class, defaults to 1 def self.code_applicability_start_year 1 end # @return [Integer] # the last year of applicability for this class, defaults to 9999 def self.code_applicability_end_year 9999 end # @return [Array of Strings of NomenclaturalRank names] # nomenclatural ranks to which this class is applicable, that is, only {TaxonName}s of these {NomenclaturalRank}s may be classified as this class def self.applicable_ranks [] end # @return [Array of Strings of TaxonNameClassification names] # the disjoint (inapplicable) {TaxonNameClassification}s for this class, that is, {TaxonName}s classified as this class can not be additionally classified under these classes def self.disjoint_taxon_name_classes [] end # @return [String, nil] # if applicable, a DWC gbif status for this class def self.gbif_status nil end def self.assignable false end #def self.common # false #end # @todo Perhaps not inherit these three meaxonNameClassificationsHelper::descendants_collection( TaxonNameClassification::Latinized )thods? # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (species) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} # used to validate gender agreement of species name with a genus def self.possible_species_endings [] end # @return [Array of Strings] # the questionable suffixes for a {TaxonName} name classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.questionable_species_endings [] end # @return [Array of Strings] # the possible suffixes for a {TaxonName} name (genus) classified as this class, for example see {TaxonNameClassification::Latinized::Gender::Masculine} def self.possible_genus_endings [] end def self.nomen_uri const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil end def set_cached set_cached_names_for_taxon_names end # TODO: move these to individual classes?! # Starting to move to individual classes # Gender is sone def set_cached_names_for_taxon_names t = taxon_name return if t.destroyed? begin TaxonName.transaction_with_retry do if type_name =~ /(Fossil|Hybrid|Candidatus)/ # Break these out, they don't all apply to the same codes n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) elsif type_name =~ /Latinized::PartOfSpeech/ n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) TaxonNameRelationship::OriginalCombination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_cached_original_combinations end TaxonNameRelationship::Combination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_column(:verbatim_name, t1.cached) if t1.verbatim_name.nil? n = t1.get_full_name t1.update_columns( cached: n, cached_html: t1.get_full_name_html(n) ) end elsif type_name =~ /Latinized::Gender/ # Handled in subclasses raise elsif TAXON_NAME_CLASS_NAMES_VALID.include?(type_name) vn = t.get_valid_taxon_name vn.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: !vn.unavailable_or_invalid?) # Do not change! vn.list_of_invalid_taxon_names.each do |s| s.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: false) s.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end end t.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end else t.update_columns(cached_is_valid: false) end if TAXON_NAME_CLASS_NAMES_UNAVAILABLE.include?( type_name ) t.update_columns( cached_is_available: false ) end end rescue ActiveRecord::RecordInvalid false end true end def validate_uniqueness_of_latinized true # moved to subclasses end def sv_proper_classification if TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type) # self.type_class is a Class if not self.type_class.applicable_ranks.include?(self.taxon_name.rank_string) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} at the rank of #{self.taxon_name.rank_class.rank_name}", success_message: 'The status was deleted', failure_message: 'Fail to delete the status') end end end def sv_fix_proper_classification begin TaxonNameClassification.transaction do self.destroy end return true rescue return false end end def sv_proper_year y = self.taxon_name.year_of_publication if !y.nil? && (y > self.type_class.code_applicability_end_year || y < self.type_class.code_applicability_start_year) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} published in the year #{y}") end end def sv_validate_disjoint_classes classifications = TaxonNameClassification.where_taxon_name(self.taxon_name).not_self(self) classifications.each do |i| soft_validations.add(:type, "The status '#{self.classification_label}' conflicting with another status: '#{i.classification_label}'") if self.type_class.disjoint_taxon_name_classes.include?(i.type_name) end end def sv_not_specific_classes true # moved to subclasses end def self.annotates? true end def annotated_object taxon_name end # @param batch_response [BatchResponse] # @param query [ActiveRecord::Relation] TaxonName scope from the filter # @param hash_query [Hash] serialized filter params, used to re-run the query in async jobs # @param mode [Symbol, String] :set, :remove_gender (gender); :add_status, :remove_status (arbitrary status) # @param params [Hash] :type required for :set, :add_status, :remove_status; # :citation (optional, :add_status only) a Hash with :source_id (required to attach), :pages, :is_original - # attached to the status whether it was just created or already existed; tolerates (does not duplicate or # error on) a citation with the same source, pages, and is_original already present on that status # @param async [Boolean] # @param project_id [Integer] # @param user_id [Integer] # @param called_from_async [Boolean] prevents re-dispatching when already inside a job # @return [BatchResponse] def self.process_batch_by_filter_scope( batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false ) async = false if called_from_async == true r = batch_response case mode.to_sym when :set # gender gender_type = params[:type] return r unless TAXON_NAME_CLASSIFICATIONS_FOR_GENDER.include?(gender_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end existing_by_taxon_name_id = TaxonNameClassification .with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER) .where(taxon_name: query) .index_by(&:taxon_name_id) query.find_each do |taxon_name| if existing = existing_by_taxon_name_id[taxon_name.id] if existing.type == gender_type # Already the requested gender - skip the update entirely rather # than trigger the expensive after_commit cascade (walks every # descendant taxon name to recompute cached spellings) for # nothing. r.updated.push existing.id elsif existing.update(type: gender_type) r.updated.push existing.id else r.not_updated.push taxon_name.id existing.errors..each { |msg| r.validation_errors[msg] += 1 } end else classification = TaxonNameClassification.create( taxon_name: taxon_name, type: gender_type ) if classification.persisted? r.updated.push classification.id else r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } end end end when :remove_gender if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end destroy_classifications_for_batch( classifications: TaxonNameClassification.with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER), query:, batch_response: r ) when :add_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end citation_params = params[:citation]&.symbolize_keys citation_source_id = citation_params && citation_params[:source_id] citation_source = citation_source_id && Source.find_by(id: citation_source_id) existing_by_taxon_name_id = TaxonNameClassification .where(type: status_type) .where(taxon_name: query) .index_by(&:taxon_name_id) # Disjoint types (e.g. Iczn::Fossil::Ichnotaxon is disjoint with its own # parent Iczn::Fossil) already satisfy this status; skip creating a # conflicting status rather than let the two coexist. disjoint_types = status_type.constantize.disjoint_taxon_name_classes conflicting_taxon_name_ids = if disjoint_types.empty? Set.new else TaxonNameClassification .where(type: disjoint_types) .where(taxon_name: query) .distinct .pluck(:taxon_name_id) .to_set end # Classifications that already carry the exact citation (same # source, pages, and is_original) being requested. This isn't just a # performance nicety: it's what distinguishes an identical repeat # (skipped and reported as updated) from a genuine conflict: same # source and pages but a different is_original (attempted, fails, # and is reported below with a message specific to that case). already_cited_classification_ids = if citation_source_id && existing_by_taxon_name_id.any? Citation.duplicate_citation_object_ids( citation_object_type: 'TaxonNameClassification', citation_object_ids: existing_by_taxon_name_id.values.map(&:id), source_id: citation_source_id, pages: citation_params[:pages], is_original: citation_params[:is_original] ) else Set.new end query.find_each do |taxon_name| if ( !existing_by_taxon_name_id.key?(taxon_name.id) && conflicting_taxon_name_ids.include?(taxon_name.id) ) r.not_updated.push taxon_name.id r.validation_errors['conflicts with an existing disjoint classification'] += 1 next end classification = existing_by_taxon_name_id[taxon_name.id] || TaxonNameClassification.create(taxon_name: taxon_name, type: status_type) unless classification.persisted? r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } next end if citation_source_id && !already_cited_classification_ids.include?(classification.id) citation = classification.citations.create( source: citation_source, pages: citation_params[:pages], is_original: citation_params[:is_original] ) unless citation.persisted? r.not_updated.push taxon_name.id # An exact repeat was already ruled out above, so a source_id # conflict here can only mean a citation with this same source # and pages exists with a different is_original - Citation's # own validation doesn't know or care about is_original, it # only reports the source/pages conflict, so the more specific # wording is built here. The taxon name id is included (rather # than summarized by count, as validation_errors normally are) # since this needs manual review to resolve. if citation.errors[:source_id].any? r.validation_errors["citation already exists with a different 'original' flag for taxon name id #{taxon_name.id} - is_original was not changed"] += 1 else # a second `is_original = true` citation, e.g. citation.errors..each { |msg| r.validation_errors[msg] += 1 } end next end end r.updated.push classification.id end when :remove_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) return r end # Only the exact type selected: not its subclasses (e.g. removing # Iczn::Fossil leaves Iczn::Fossil::Ichnotaxon), and not # disjoint_taxon_name_classes, which is every *conflicting* status. destroy_classifications_for_batch( classifications: TaxonNameClassification.where(type: status_type), query:, batch_response: r ) end r end # Destroys `classifications` belonging to taxon names in `query`. # Iterates every taxon name in the query (not just ones with a matching # classification) so updated/not_updated always account for the full # total_attempted. A taxon name with nothing to remove lands in # not_updated with no validation_errors entry; if a destroy were ever to # fail (nothing currently blocks one) it would also land in not_updated, # but with an error message - that's how the two would be told apart. def self.destroy_classifications_for_batch(classifications:, query:, batch_response:) existing_by_taxon_name_id = classifications .where(taxon_name: query) .includes(:taxon_name) # used by the set_cached callback .group_by(&:taxon_name_id) query.find_each do |taxon_name| found = existing_by_taxon_name_id[taxon_name.id] || [] if found.empty? batch_response.not_updated.push taxon_name.id next end failed = found.reject do |c| c.destroy # destroy is necessary to update cached values c.destroyed? end if failed.empty? batch_response.updated.push nil else # never happens? batch_response.not_updated.push taxon_name.id failed.each { |c| c.errors..each { |msg| batch_response.validation_errors[msg] += 1 } } end end end def self.dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) BatchByFilterScopeJob.perform_later( klass: self.name, hash_query:, mode:, params:, project_id:, user_id: ) end private def nomenclature_code_matches if taxon_name && type && nomenclature_code tn = taxon_name.is_combination? ? taxon_name.protonyms.last : taxon_name nc = tn.rank_class.nomenclatural_code if nomenclature_code != nc taxon_name_code = nc.nil? ? 'no' : "the #{nc}" errors.add(:taxon_name, "#{taxon_name.cached_html} belongs to #{taxon_name_code} nomenclatural code, but the status is from the #{nomenclature_code} nomenclatural code") end end end # TODO: unnecessary! Type handling will raise here def validate_taxon_name_classification errors.add(:type, 'Status not found') if !self.type.nil? and !TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type.to_s) end # @todo move these to a shared library (see NomenclaturalRank too) def self.collect_to_s(*args) args.collect{|arg| arg.to_s} end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_to_s(*classes) ans = [] classes.each do |klass| ans += klass.descendants.collect{|k| k.to_s} end ans end # @todo move these to a shared library (see NomenclaturalRank too) # !! using this strongly suggests something can be optimized, meomized etc. def self.collect_descendants_and_itself_to_s(*classes) classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes) end # Force loading all descendants as soon as this class is referenced Dir.glob("#{Rails.root}/app/models/taxon_name_classification/**/*.rb") .sort { |a, b| a.split('/').count <=> b.split('/').count } .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') } .map { |p| p.split('/') } .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } } .map { |c| c.join('::') }.map(&:constantize) end |
Class Method Details
.annotates? ⇒ Boolean
299 300 301 |
# File 'app/models/taxon_name_classification.rb', line 299 def self.annotates? true end |
.applicable_ranks ⇒ Array of Strings of NomenclaturalRank names
nomenclatural ranks to which this class is applicable, that is, only TaxonNames of these NomenclaturalRanks may be classified as this class
131 132 133 |
# File 'app/models/taxon_name_classification.rb', line 131 def self.applicable_ranks [] end |
.assignable ⇒ Object
147 148 149 |
# File 'app/models/taxon_name_classification.rb', line 147 def self.assignable false end |
.code_applicability_end_year ⇒ Integer
the last year of applicability for this class, defaults to 9999
125 126 127 |
# File 'app/models/taxon_name_classification.rb', line 125 def self.code_applicability_end_year 9999 end |
.code_applicability_start_year ⇒ Integer
the minimum year of applicability for this class, defaults to 1
119 120 121 |
# File 'app/models/taxon_name_classification.rb', line 119 def self.code_applicability_start_year 1 end |
.collect_descendants_and_itself_to_s(*classes) ⇒ Object
move these to a shared library (see NomenclaturalRank too)
!! using this strongly suggests something can be optimized, meomized etc.
608 609 610 |
# File 'app/models/taxon_name_classification.rb', line 608 def self.collect_descendants_and_itself_to_s(*classes) classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes) end |
.collect_descendants_to_s(*classes) ⇒ Object
move these to a shared library (see NomenclaturalRank too)
!! using this strongly suggests something can be optimized, meomized etc.
598 599 600 601 602 603 604 |
# File 'app/models/taxon_name_classification.rb', line 598 def self.collect_descendants_to_s(*classes) ans = [] classes.each do |klass| ans += klass.descendants.collect{|k| k.to_s} end ans end |
.collect_to_s(*args) ⇒ Object
move these to a shared library (see NomenclaturalRank too)
592 593 594 |
# File 'app/models/taxon_name_classification.rb', line 592 def self.collect_to_s(*args) args.collect{|arg| arg.to_s} end |
.destroy_classifications_for_batch(classifications:, query:, batch_response:) ⇒ Object
Destroys classifications belonging to taxon names in query.
Iterates every taxon name in the query (not just ones with a matching
classification) so updated/not_updated always account for the full
total_attempted. A taxon name with nothing to remove lands in
not_updated with no validation_errors entry; if a destroy were ever to
fail (nothing currently blocks one) it would also land in not_updated,
but with an error message - that's how the two would be told apart.
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
# File 'app/models/taxon_name_classification.rb', line 530 def self.destroy_classifications_for_batch(classifications:, query:, batch_response:) existing_by_taxon_name_id = classifications .where(taxon_name: query) .includes(:taxon_name) # used by the set_cached callback .group_by(&:taxon_name_id) query.find_each do |taxon_name| found = existing_by_taxon_name_id[taxon_name.id] || [] if found.empty? batch_response.not_updated.push taxon_name.id next end failed = found.reject do |c| c.destroy # destroy is necessary to update cached values c.destroyed? end if failed.empty? batch_response.updated.push nil else # never happens? batch_response.not_updated.push taxon_name.id failed.each { |c| c.errors..each { |msg| batch_response.validation_errors[msg] += 1 } } end end end |
.disjoint_taxon_name_classes ⇒ Array of Strings of TaxonNameClassification names
the disjoint (inapplicable) TaxonNameClassifications for this class, that is, TaxonNames classified as this class can not be additionally classified under these classes
137 138 139 |
# File 'app/models/taxon_name_classification.rb', line 137 def self.disjoint_taxon_name_classes [] end |
.dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) ⇒ Object
562 563 564 565 566 567 568 569 570 571 |
# File 'app/models/taxon_name_classification.rb', line 562 def self.dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) BatchByFilterScopeJob.perform_later( klass: self.name, hash_query:, mode:, params:, project_id:, user_id: ) end |
.gbif_status ⇒ String?
Returns if applicable, a DWC gbif status for this class.
143 144 145 |
# File 'app/models/taxon_name_classification.rb', line 143 def self.gbif_status nil end |
.label ⇒ Object
73 74 75 |
# File 'app/models/taxon_name_classification.rb', line 73 def self.label name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish end |
.nomen_uri ⇒ Object
176 177 178 |
# File 'app/models/taxon_name_classification.rb', line 176 def self.nomen_uri const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil end |
.parent ⇒ Object
Returns class this method calls Module#module_parent.
79 80 81 |
# File 'app/models/taxon_name_classification.rb', line 79 def self.parent self.module_parent end |
.possible_genus_endings ⇒ Array of Strings
the possible suffixes for a TaxonName name (genus) classified as this class, for example see TaxonNameClassification::Latinized::Gender::Masculine
172 173 174 |
# File 'app/models/taxon_name_classification.rb', line 172 def self.possible_genus_endings [] end |
.possible_species_endings ⇒ Array of Strings
Returns the possible suffixes for a TaxonName name (species) classified as this class, for example see TaxonNameClassification::Latinized::Gender::Masculine used to validate gender agreement of species name with a genus.
160 161 162 |
# File 'app/models/taxon_name_classification.rb', line 160 def self.possible_species_endings [] end |
.process_batch_by_filter_scope(batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false) ⇒ BatchResponse
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'app/models/taxon_name_classification.rb', line 320 def self.process_batch_by_filter_scope( batch_response: nil, query: nil, hash_query: nil, mode: nil, params: nil, async: nil, project_id: nil, user_id: nil, called_from_async: false ) async = false if called_from_async == true r = batch_response case mode.to_sym when :set # gender gender_type = params[:type] return r unless TAXON_NAME_CLASSIFICATIONS_FOR_GENDER.include?(gender_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end existing_by_taxon_name_id = TaxonNameClassification .with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER) .where(taxon_name: query) .index_by(&:taxon_name_id) query.find_each do |taxon_name| if existing = existing_by_taxon_name_id[taxon_name.id] if existing.type == gender_type # Already the requested gender - skip the update entirely rather # than trigger the expensive after_commit cascade (walks every # descendant taxon name to recompute cached spellings) for # nothing. r.updated.push existing.id elsif existing.update(type: gender_type) r.updated.push existing.id else r.not_updated.push taxon_name.id existing.errors..each { |msg| r.validation_errors[msg] += 1 } end else classification = TaxonNameClassification.create( taxon_name: taxon_name, type: gender_type ) if classification.persisted? r.updated.push classification.id else r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } end end end when :remove_gender if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end destroy_classifications_for_batch( classifications: TaxonNameClassification.with_type_array(TAXON_NAME_CLASSIFICATIONS_FOR_GENDER), query:, batch_response: r ) when :add_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job( hash_query:, mode:, params:, project_id:, user_id: ) return r end citation_params = params[:citation]&.symbolize_keys citation_source_id = citation_params && citation_params[:source_id] citation_source = citation_source_id && Source.find_by(id: citation_source_id) existing_by_taxon_name_id = TaxonNameClassification .where(type: status_type) .where(taxon_name: query) .index_by(&:taxon_name_id) # Disjoint types (e.g. Iczn::Fossil::Ichnotaxon is disjoint with its own # parent Iczn::Fossil) already satisfy this status; skip creating a # conflicting status rather than let the two coexist. disjoint_types = status_type.constantize.disjoint_taxon_name_classes conflicting_taxon_name_ids = if disjoint_types.empty? Set.new else TaxonNameClassification .where(type: disjoint_types) .where(taxon_name: query) .distinct .pluck(:taxon_name_id) .to_set end # Classifications that already carry the exact citation (same # source, pages, and is_original) being requested. This isn't just a # performance nicety: it's what distinguishes an identical repeat # (skipped and reported as updated) from a genuine conflict: same # source and pages but a different is_original (attempted, fails, # and is reported below with a message specific to that case). already_cited_classification_ids = if citation_source_id && existing_by_taxon_name_id.any? Citation.duplicate_citation_object_ids( citation_object_type: 'TaxonNameClassification', citation_object_ids: existing_by_taxon_name_id.values.map(&:id), source_id: citation_source_id, pages: citation_params[:pages], is_original: citation_params[:is_original] ) else Set.new end query.find_each do |taxon_name| if ( !existing_by_taxon_name_id.key?(taxon_name.id) && conflicting_taxon_name_ids.include?(taxon_name.id) ) r.not_updated.push taxon_name.id r.validation_errors['conflicts with an existing disjoint classification'] += 1 next end classification = existing_by_taxon_name_id[taxon_name.id] || TaxonNameClassification.create(taxon_name: taxon_name, type: status_type) unless classification.persisted? r.not_updated.push taxon_name.id classification.errors..each { |msg| r.validation_errors[msg] += 1 } next end if citation_source_id && !already_cited_classification_ids.include?(classification.id) citation = classification.citations.create( source: citation_source, pages: citation_params[:pages], is_original: citation_params[:is_original] ) unless citation.persisted? r.not_updated.push taxon_name.id # An exact repeat was already ruled out above, so a source_id # conflict here can only mean a citation with this same source # and pages exists with a different is_original - Citation's # own validation doesn't know or care about is_original, it # only reports the source/pages conflict, so the more specific # wording is built here. The taxon name id is included (rather # than summarized by count, as validation_errors normally are) # since this needs manual review to resolve. if citation.errors[:source_id].any? r.validation_errors["citation already exists with a different 'original' flag for taxon name id #{taxon_name.id} - is_original was not changed"] += 1 else # a second `is_original = true` citation, e.g. citation.errors..each { |msg| r.validation_errors[msg] += 1 } end next end end r.updated.push classification.id end when :remove_status status_type = params[:type] return r unless TAXON_NAME_CLASSIFICATION_NAMES.include?(status_type) if async && !called_from_async dispatch_batch_by_filter_scope_job(hash_query:, mode:, params:, project_id:, user_id:) return r end # Only the exact type selected: not its subclasses (e.g. removing # Iczn::Fossil leaves Iczn::Fossil::Ichnotaxon), and not # disjoint_taxon_name_classes, which is every *conflicting* status. destroy_classifications_for_batch( classifications: TaxonNameClassification.where(type: status_type), query:, batch_response: r ) end r end |
.questionable_species_endings ⇒ Array of Strings
Returns the questionable suffixes for a TaxonName name classified as this class, for example see TaxonNameClassification::Latinized::Gender::Masculine.
166 167 168 |
# File 'app/models/taxon_name_classification.rb', line 166 def self.questionable_species_endings [] end |
Instance Method Details
#annotated_object ⇒ Object
303 304 305 |
# File 'app/models/taxon_name_classification.rb', line 303 def annotated_object taxon_name end |
#classification_label ⇒ String
Returns a humanized class name, with code appended to differentiate !! explored idea of LABEL in individual subclasses, use this if this doesn't work this is helper-esqe, but also useful in validation, so here for now.
103 104 105 106 107 |
# File 'app/models/taxon_name_classification.rb', line 103 def classification_label return nil if type_name.nil? type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish #+ #(nomenclature_code ? " [#{nomenclature_code}]" : '') end |
#nomen_id ⇒ String
Returns the NOMEN id for this classification.
111 112 113 |
# File 'app/models/taxon_name_classification.rb', line 111 def nomen_id self.class::NOMEN_URI.split('/').last end |
#nomenclature_code ⇒ Object
65 66 67 68 69 70 71 |
# File 'app/models/taxon_name_classification.rb', line 65 def nomenclature_code return :iczn if type.match(/::Iczn/) return :icnp if type.match(/::Icnp/) return :icvcn if type.match(/::Icvcn/) return :icn if type.match(/::Icn/) return nil end |
#nomenclature_code_matches ⇒ Object (private)
575 576 577 578 579 580 581 582 583 584 |
# File 'app/models/taxon_name_classification.rb', line 575 def nomenclature_code_matches if taxon_name && type && nomenclature_code tn = taxon_name.is_combination? ? taxon_name.protonyms.last : taxon_name nc = tn.rank_class.nomenclatural_code if nomenclature_code != nc taxon_name_code = nc.nil? ? 'no' : "the #{nc}" errors.add(:taxon_name, "#{taxon_name.cached_html} belongs to #{taxon_name_code} nomenclatural code, but the status is from the #{nomenclature_code} nomenclatural code") end end end |
#set_cached ⇒ Object
180 181 182 |
# File 'app/models/taxon_name_classification.rb', line 180 def set_cached set_cached_names_for_taxon_names end |
#set_cached_names_for_taxon_names ⇒ Object
TODO: move these to individual classes?! Starting to move to individual classes Gender is sone
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'app/models/taxon_name_classification.rb', line 187 def set_cached_names_for_taxon_names t = taxon_name return if t.destroyed? begin TaxonName.transaction_with_retry do if type_name =~ /(Fossil|Hybrid|Candidatus)/ # Break these out, they don't all apply to the same codes n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) elsif type_name =~ /Latinized::PartOfSpeech/ n = t.get_full_name t.update_columns( cached: n, cached_html: t.get_full_name_html(n), cached_original_combination: t.get_original_combination, cached_original_combination_html: t.get_original_combination_html ) TaxonNameRelationship::OriginalCombination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_cached_original_combinations end TaxonNameRelationship::Combination.where(subject_taxon_name: t).collect{|i| i.object_taxon_name}.uniq.each do |t1| t1.update_column(:verbatim_name, t1.cached) if t1.verbatim_name.nil? n = t1.get_full_name t1.update_columns( cached: n, cached_html: t1.get_full_name_html(n) ) end elsif type_name =~ /Latinized::Gender/ # Handled in subclasses raise elsif TAXON_NAME_CLASS_NAMES_VALID.include?(type_name) vn = t.get_valid_taxon_name vn.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: !vn.unavailable_or_invalid?) # Do not change! vn.list_of_invalid_taxon_names.each do |s| s.update_columns( cached_valid_taxon_name_id: vn.id, cached_is_valid: false) s.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end end t.combination_list_self.each do |c| c.update_columns(cached_valid_taxon_name_id: vn.id) end else t.update_columns(cached_is_valid: false) end if TAXON_NAME_CLASS_NAMES_UNAVAILABLE.include?( type_name ) t.update_columns( cached_is_available: false ) end end rescue ActiveRecord::RecordInvalid false end true end |
#sv_fix_proper_classification ⇒ Object
270 271 272 273 274 275 276 277 278 279 |
# File 'app/models/taxon_name_classification.rb', line 270 def sv_fix_proper_classification begin TaxonNameClassification.transaction do self.destroy end return true rescue return false end end |
#sv_not_specific_classes ⇒ Object
295 296 297 |
# File 'app/models/taxon_name_classification.rb', line 295 def sv_not_specific_classes true # moved to subclasses end |
#sv_proper_classification ⇒ Object
261 262 263 264 265 266 267 268 |
# File 'app/models/taxon_name_classification.rb', line 261 def sv_proper_classification if TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type) # self.type_class is a Class if not self.type_class.applicable_ranks.include?(self.taxon_name.rank_string) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} at the rank of #{self.taxon_name.rank_class.rank_name}", success_message: 'The status was deleted', failure_message: 'Fail to delete the status') end end end |
#sv_proper_year ⇒ Object
281 282 283 284 285 286 |
# File 'app/models/taxon_name_classification.rb', line 281 def sv_proper_year y = self.taxon_name.year_of_publication if !y.nil? && (y > self.type_class.code_applicability_end_year || y < self.type_class.code_applicability_start_year) soft_validations.add(:type, "The status '#{self.classification_label}' is not applicable to the taxon #{self.taxon_name.cached_html} published in the year #{y}") end end |
#sv_validate_disjoint_classes ⇒ Object
288 289 290 291 292 293 |
# File 'app/models/taxon_name_classification.rb', line 288 def sv_validate_disjoint_classes classifications = TaxonNameClassification.where_taxon_name(self.taxon_name).not_self(self) classifications.each do |i| soft_validations.add(:type, "The status '#{self.classification_label}' conflicting with another status: '#{i.classification_label}'") if self.type_class.disjoint_taxon_name_classes.include?(i.type_name) end end |
#type_class ⇒ Object
94 95 96 97 |
# File 'app/models/taxon_name_classification.rb', line 94 def type_class r = read_attribute(:type).to_s r = ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r.safe_constantize : nil end |
#type_class=(value) ⇒ Object
90 91 92 |
# File 'app/models/taxon_name_classification.rb', line 90 def type_class=(value) write_attribute(:type, value.to_s) end |
#type_name ⇒ String
Returns the class name, "validated" against the known list of names.
85 86 87 88 |
# File 'app/models/taxon_name_classification.rb', line 85 def type_name r = self.type.to_s ::TAXON_NAME_CLASSIFICATION_NAMES.include?(r) ? r : nil end |
#validate_taxon_name_classification ⇒ Object (private)
TODO: unnecessary! Type handling will raise here
587 588 589 |
# File 'app/models/taxon_name_classification.rb', line 587 def validate_taxon_name_classification errors.add(:type, 'Status not found') if !self.type.nil? and !TAXON_NAME_CLASSIFICATION_NAMES.include?(self.type.to_s) end |
#validate_uniqueness_of_latinized ⇒ Object
257 258 259 |
# File 'app/models/taxon_name_classification.rb', line 257 def validate_uniqueness_of_latinized true # moved to subclasses end |