Class: TaxonName

Inherits:
ApplicationRecord show all
Includes:
Housekeeping, Shared::AlternateValues, Shared::Citations, Shared::Confidences, Shared::DataAttributes, Shared::Depictions, Shared::HasPapertrail, Shared::HasRoles, Shared::Identifiers, Shared::IsData, Shared::Notes, Shared::Tags, SoftValidation
Defined in:
app/models/taxon_name.rb

Direct Known Subclasses

Combination, Hybrid

Constant Summary

ALTERNATE_VALUES_FOR =

Allows users to provide arbitrary annotations that “over-ride” rank string

[:rank_class].freeze
EXCEPTED_FORM_TAXON_NAME_CLASSIFICATIONS =

TODO: Move to taxon name classification.rb

[
  'TaxonNameClassification::Iczn::Unavailable::NotLatin',
  'TaxonNameClassification::Iczn::Unavailable::LessThanTwoLetters',
  'TaxonNameClassification::Iczn::Unavailable::NotLatinizedAfter1899',
  'TaxonNameClassification::Iczn::Unavailable::NotLatinizedBefore1900AndNotAccepted',
  'TaxonNameClassification::Iczn::Unavailable::NonBinomial'
  #'TaxonNameClassification::Iczn::Available::Invalid::FamilyGroupNameForm'
].freeze
EXCEPTED_FORM_TAXON_NAME_RELATIONSHIPS =
[
  'TaxonNameRelationship::Icn::Unaccepting::Usage::Misspelling',
  'TaxonNameRelationship::Icnp::Unaccepting::Usage::Misspelling',
  'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm',
  'TaxonNameRelationship::Iczn::Invalidating::Usage::IncorrectOriginalSpelling',
  'TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling'
].freeze
COMBINATION_ELEMENTS =
[:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze
SPECIES_EPITHET_RANKS =
%w{species subspecies variety subvariety form subform}.freeze
NOT_LATIN =

Dash is allowed?

Regexp.new(/[^a-zA-Z|\-]/).freeze
NO_CACHED_MESSAGE =
'REBUILD PROJECT TAXON NAME CACHE'.freeze

Constants included from SoftValidation

SoftValidation::ANCESTORS_WITH_SOFT_VALIDATIONS

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from SoftValidation

#clear_soft_validations, #fix_soft_validations, #soft_fixed?, #soft_valid?, #soft_validate, #soft_validated?, #soft_validations

Methods included from Housekeeping

#has_polymorphic_relationship?

Instance Attribute Details

- (Boolean) also_create_otu

Returns When true, also creates an OTU that is tied to this taxon name

Returns:

  • (Boolean)

    When true, also creates an OTU that is tied to this taxon name



180
181
182
# File 'app/models/taxon_name.rb', line 180

def also_create_otu
  @also_create_otu
end

- (String) cached_classified_as

if the name was classified in different group (e.g. a genus placed in wrong family).

Returns:

  • (String)


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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
# File 'app/models/taxon_name.rb', line 128

class TaxonName < ApplicationRecord

  has_closure_tree

  include Housekeeping
  include Shared::DataAttributes
  include Shared::HasRoles
  include Shared::Tags
  include Shared::Identifiers
  include Shared::Notes
  include Shared::Depictions
  include Shared::Citations
  include Shared::Confidences
  include Shared::AlternateValues
  include Shared::HasPapertrail
  include SoftValidation
  include Shared::IsData

  # Allows users to provide arbitrary annotations that "over-ride" rank string
  ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name`

  # TODO: Move to taxon name classification.rb
  EXCEPTED_FORM_TAXON_NAME_CLASSIFICATIONS = [
    'TaxonNameClassification::Iczn::Unavailable::NotLatin',
    'TaxonNameClassification::Iczn::Unavailable::LessThanTwoLetters',
    'TaxonNameClassification::Iczn::Unavailable::NotLatinizedAfter1899',
    'TaxonNameClassification::Iczn::Unavailable::NotLatinizedBefore1900AndNotAccepted',
    'TaxonNameClassification::Iczn::Unavailable::NonBinomial'
    #'TaxonNameClassification::Iczn::Available::Invalid::FamilyGroupNameForm'
  ].freeze

  EXCEPTED_FORM_TAXON_NAME_RELATIONSHIPS = [
    'TaxonNameRelationship::Icn::Unaccepting::Usage::Misspelling',
    'TaxonNameRelationship::Icnp::Unaccepting::Usage::Misspelling',
    'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm',
    'TaxonNameRelationship::Iczn::Invalidating::Usage::IncorrectOriginalSpelling',
    'TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling'
  ].freeze

  COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze

  SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze

  NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed?

  NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze

  delegate :nomenclatural_code, to: :rank_class, allow_nil: true
  delegate :rank_name, to: :rank_class, allow_nil: true

  # @return [Boolean]
  #   When true, also creates an OTU that is tied to this taxon name
  attr_accessor :also_create_otu

  # @return [Boolean]
  #   When true cached values are not built
  attr_accessor :no_cached

  after_save :create_new_combination_if_absent
  after_save :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? }
  after_save :set_cached_warnings, if: Proc.new {|n| n.no_cached }

  after_create :create_otu, if: :also_create_otu

  before_destroy :check_for_children, prepend: true

  validate :validate_rank_class_class,
    # :check_format_of_name,
    :validate_parent_rank_is_higher,
    :validate_parent_from_the_same_project,
    :validate_parent_is_set,
    :check_new_rank_class,
    :check_new_parent_class,
    :validate_source_type,
    :validate_one_root_per_project

  validates_presence_of :type, message: 'is not specified'

  # TODO: move some of these down to Protonym when they don't apply to Combination

  # TODO: think of a different name, and test
  has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id

  belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id
  has_one :source_classified_as_relationship, -> {
    where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'})
  }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id

  has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name

  has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error
  has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name

  has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy
  has_many :taxon_name_authors, through: :taxon_name_author_roles, source: :person
  has_many :taxon_name_classifications, dependent: :destroy, foreign_key: :taxon_name_id, inverse_of: :taxon_name
  has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name

  # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see.  Placement is after has_many relationships. (?)
  accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? }
  accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true
  accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank?  }


  scope :that_is_valid, -> { where('taxon_names.id = taxon_names.cached_valid_taxon_name_id') }
  scope :that_is_invalid, -> { where.not('taxon_names.id = taxon_names.cached_valid_taxon_name_id') }



  scope :with_type, -> (type) {where(type: type)}

  scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )}

  scope :ancestors_of, -> (taxon_name) {
    joins(:descendant_hierarchies)
      .where(taxon_name_hierarchies: {descendant_id: taxon_name.id})
      .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id)
      .order('taxon_name_hierarchies.generations DESC') # root is at index 0
  }

  # LEAVE UNORDERED, if you want order:
  #   .order('taxon_name_hierarchies.generations DESC')
  scope :self_and_ancestors_of, -> (taxon_name) {
    joins(:descendant_hierarchies)
      .where(taxon_name_hierarchies: {descendant_id: taxon_name.id})
  }
  # Includes taxon_name, doesn't order result
  scope :ancestors_and_descendants_of, -> (taxon_name) do
    a = TaxonName.self_and_ancestors_of(taxon_name)
    b = TaxonName.descendants_of(taxon_name)
    TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names")
  end

  scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) }
  scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) }
  scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") }
  scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") }
  scope :project_root, -> (root_id) {where("(taxon_names.rank_class = 'NomenclaturalRank' AND taxon_names.project_id = ?)", root_id)}

  # A specific relationship
  scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) }
  scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) }
  scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) }
  scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) }
  scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) }
  scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) }
  scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) }

  def self.with_taxon_name_relationship(relationship)
    a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship})
    b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship})
    TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names")
  end

  scope :with_taxon_name_relationships, -> {
    joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id').
    joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id').
    where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL')
  }
  # *Any* relationship where there IS a relationship for a subject/object/both
  scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) }
  scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) }

  # *Any* relationship where there is NOT a relationship for a subject/object/both
  scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) }
  scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) }

  scope :without_taxon_name_relationships, -> {
    joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id').
    joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id').
    where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL')
  }

  # TODO: deprecate all of these for where()
  scope :with_parent_id, -> (parent_id) {where(parent_id: parent_id)}
  scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id: cached_valid_taxon_name_id)}
  scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) }
  scope :with_cached_html, -> (html) { where(cached_html: html) } # WHY? - DEPRECATE for cached

  # @return [Scope] Protonym(s) the **broad sense** synonyms of this name
  def synonyms
    TaxonName.with_cached_valid_taxon_name_id(self.id)
  end

  soft_validate(:sv_validate_name, set: :validate_name)
  soft_validate(:sv_missing_fields, set: :missing_fields)
  soft_validate(:sv_parent_is_valid_name, set: :parent_is_valid_name)
  soft_validate(:sv_cached_names, set: :cached_names)
  soft_validate(:sv_not_synonym_of_self, set: :not_synonym_of_self)
  soft_validate(:sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms)
  soft_validate(:sv_incomplete_combination, set: :incomplete_combination)

  # @return [Array of TaxonName]
  #   ordered by rank, a scope-like hack
  def self.sort_by_rank(taxon_names)
    taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)}
  end

  # @return [String]
  #   rank as human readable shortform, like 'genus' or 'species'
  def rank
    ::RANKS.include?(rank_string) ? rank_name : nil
  end

  # @return [String]
  #   rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species}
  def rank_string
    read_attribute(:rank_class)
  end

  def rank_class=(value)
    write_attribute(:rank_class, value.to_s)
  end

  # @return [NomenclaturalRank class]
  #   rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species}
  def rank_class
    r = read_attribute(:rank_class)
    Ranks.valid?(r) ? r.safe_constantize : r
  end

  # @return [Array]
  #   all TaxonNameRelationships where this taxon is an object or subject.
  def all_taxon_name_relationships
    # !! If self relationships are ever made possible this needs a DISTINCT clause
    TaxonNameRelationship.find_by_sql(
      "SELECT taxon_name_relationships.*
         FROM taxon_name_relationships
         WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id}
       UNION
       SELECT taxon_name_relationships.*
         FROM taxon_name_relationships
         WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}")
  end

  # @return [Array of TaxonName]
  #   all taxon_names which have relationships to this taxon as an object or subject.
  def related_taxon_names
    TaxonName.find_by_sql(
      "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id}
      UNION
      SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}"
    )
  end

  # @return [String, nil]
  #   the baseline means of displaying name authorship, i.e. the author for this taxon, last name only.
  # Important, string format priority is 1) as provided verbatim, 2) as generated from people, and 3) as taken from the source.
  def author_string
    return verbatim_author if !verbatim_author.nil?
    return Utilities::Strings.authorship_sentence( taxon_name_authors.order('roles.position').pluck(:last_name) ) if taxon_name_authors.any?
    return source.authority_name if !source.nil?
    nil
  end

  # @return [Integer]
  #   a 4 digit integer representing year of publication, like 1974
  def year_integer
    return year_of_publication if !year_of_publication.nil?
    try(:source).try(:year)
  end

  # @return [Time]
  #   effective date of publication, used to determine nomenclatural priority
  def nomenclature_date
    return nil if self.id.nil?
     family_before_1961 = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961').first

    # family_before_1961 = taxon_name_relationships.with_type_string('TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961').first
    if family_before_1961.nil?
      year = self.year_of_publication ? Time.utc(self.year_of_publication, 12, 31) : nil
      self.source ? (self.source.cached_nomenclature_date ? self.source.nomenclature_date : year) : year
    else
      obj  = family_before_1961.object_taxon_name
      year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil
      obj.source ? (self.source.cached_nomenclature_date ? obj.source.nomenclature_date : year) : year
    end
  end

  # @return [Class, nil]
  #   gender of a genus as class
  def gender_class
    gender_instance.try(:type_class)
  end

  # @return [TaxonNameClassification instance, nil]
  #    the gender classification of this name, if provided
  def gender_instance
    taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first
  end

  # @return [String, nil]
  #    gender as a string (only applicable to Genera)
  def gender_name
    gender_instance.try(:classification_label).try(:downcase)
  end

  # @return [Class]
  #   part of speech of a species as class.
  def part_of_speech_class
    part_of_speech_instance.try(:type_class)
  end

  def part_of_speech_instance
    taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first
  end

  # @return [String]
  #   part of speech of a species as string.
  def part_of_speech_name
    part_of_speech_instance.try(:classification_label).try(:downcase)
  end

  # @return [Array of String]
  #   the unique string labels derived from TaxonNameClassifications
  def statuses_from_classifications
    list = taxon_name_classifications_for_statuses
    list.empty? ? [] : list.collect{|c| c.classification_label }.sort
  end

  # @return [Scope]
  def taxon_name_classifications_for_statuses
    taxon_name_classifications.with_type_array(ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNB_TAXON_NAME_CLASSIFICATION_NAMES + ICTV_TAXON_NAME_CLASSIFICATION_NAMES)
  end

  # @return [Array of String]
  #   the unique string labels derived from and TaxonNameRelationships
  def statuses_from_relationships
    list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES)
    list.empty? ? [] : list.collect{|c| c.subject_status}.sort
  end

  # @return [Array of String]
  #   the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships
  def combined_statuses
    (statuses_from_classifications + statuses_from_relationships).uniq.sort
  end

  # @return [Array of Protonym]
  #   all of the names this name has been in in combinations
  def combination_list_all
    taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq
  end

  # @return [Array of Protonym]
  #   for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?)
  def combination_list_self
    combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self}
  end

  # @return [String]
  #   combination of cached_html and cached_author_year.
  def cached_html_name_and_author_year
    [cached_html, cached_author_year].compact.join(' ')
  end

  # @return [String] combination of cached and cached_author_year.
 def cached_name_and_author_year
   [cached, cached_author_year].compact.join(' ')
 end

  # @return [TaxonName, nil] an ancestor at the specified rank
 def ancestor_at_rank(rank)
   ancestors.with_rank_class(
     Ranks.lookup(nomenclatural_code, rank)
   ).first
 end

  # @return [Array of TaxonName] ancestors of type 'Protonym'
  def ancestor_protonyms
    Protonym.ancestors_of(self)
  end

  # @return [Array of TaxonName] descendants of type 'Protonym'
  def descendant_protonyms
    Protonym.descendants_of(self)
  end

  # @return [Boolean]
  #   true if there is a relationship where then name is asserted to be invalid
  def relationship_invalid?
    !first_possible_valid_taxon_name_relationship.nil?
  end

  # @return [Boolean]
  #  true if this name has any classification asserting that it is valid
  def classification_valid?
    taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty?
  end

  # @return [Boolean]
  #  whether this name has any classification asserting that this the name is NOT valid or that it is unavailable
  def classification_invalid_or_unavailable?
    taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any?
  end

  #  @return [Boolean]
  #     return true if name is unavailable OR invalid, else false, checks both classifications and relationships
  def unavailable_or_invalid?
    return false if classification_valid?
    classification_invalid_or_unavailable? || relationship_invalid?
  end

  # @return [Boolean]
  #   after all inference on the validity of a name, the result is stored
  #   in cached_valid_taxon_name_id, #is_valid checks that result
  def is_valid?
    id == cached_valid_taxon_name_id
  end

  # @return [Boolean]
  #   whether this name needs italics applied
  def is_italicized?
    is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) 
  end

  def is_protonym?
    type == 'Protonym'
  end

  def is_combination?
    type == 'Combination'
  end

  # @return [True|False]
  #   true if this name has a TaxonNameClassification of Fossil
  def is_fossil?
    taxon_name_classifications.with_type_contains('::Fossil').any?
  end

  # @return [Boolean]
  #   true if this name has a TaxonNameClassification of hybrid
  def is_hybrid?
    taxon_name_classifications.where_taxon_name(self).with_type_contains('Hybrid').any?
  end

  # @return [True|False]
  #   true if this name has a TaxonNameClassification of candidatus
  def is_candidatus?
    return false unless rank_string =~ /Icnp/
    taxon_name_classifications.where_taxon_name(self).with_type_contains('Candidatus').any?
  end

  # @return [True|False]
  #   true if this name has a TaxonNameClassification of not_binomial
  def not_binomial?
    taxon_name_classifications.where_taxon_name(self).with_type_contains('NonBinomial').any?
  end

  # @return [Boolean]
  #  see subclasses
  def is_genus_or_species_rank?
    false
  end

  # @return [TaxonName]
  #  a valid taxon_name for an invalid name or self for valid name.
  #  a stub here - See Protonym and Combination
  def get_valid_taxon_name
    nil
  end

  # @return [TaxonNameRelationship]
  #  returns youngest taxon name relationship where self is the subject.
  def first_possible_valid_taxon_name_relationship
    taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation
  end

  # @return [TaxonName]
  #    returns the youngest #object_taxon_name from the youngest taxon name relationship.
  def first_possible_valid_taxon_name
    return self if !unavailable_or_invalid?                      # catches all cases where no Classifications or Relationships are provided
    relationship = first_possible_valid_taxon_name_relationship
    relationship.nil? ? self : relationship.object_taxon_name    # ?! probably the if is caught by unavailable_or_invalid already
   end

  # @return [Array of TaxonName]
  #  returns list of invalid names for a given taxon.
  # TODO: Can't we just use #valid_id now?
  def list_of_invalid_taxon_names
    first_pass = true
    list = {}
    while first_pass || !list.keys.select{|t| list[t] == false}.empty? do
      first_pass = false
      list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false}
      list_of_taxa_to_check.each do |t|
        potentialy_invalid_relationships = t.related_taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first
        potentialy_invalid_relationships.find_each do |r|
          if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty?
            # do nothing, taxon has a status of valid name
          elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship
            list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil?
          end

        end
        list[t] = true if list[t] == false
      end
    end
    return [] if list.empty?
    list.sort_by{|t, a| (t.nomenclature_date || Time.now)}.collect{|t, a| t}
  end

  def gbif_status_array
    return nil if self.class.nil?
    return ['combination'] if self.class == 'Combination'
    s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact
    return s1 unless s1.empty?
    s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject}
    s3 = related_taxon_name_relationships.collect{|r| r.class.gbif_status_of_object}

    s = s2 + s3
    s.compact!
    return ['valid'] if s.empty?
    s
  end

  # @return [Array of Strings]
  #   names of all genera where the species was placed
  def name_in_gender(gender = nil)
    case gender
      when 'masculine'
        n = masculine_name
      when 'feminine'
        n = feminine_name
      when 'neuter'
        n = neuter_name
      else
        n = nil
    end
    n = n.blank? ? name : n
    return n
  end

  def create_new_combination_if_absent
    return true unless type == 'Protonym'
    if !TaxonName.with_cached_html(cached_html).count == 0
      begin
        TaxonName.transaction do
          c = Combination.new
          safe_self_and_ancestors.each do |i|
            case i.rank
              when 'genus'
                c.genus = i
              when 'subgenus'
                c.subgenus = i
              when 'species'
                c.species = i
              when 'subspecies'
                c.subspecies = i
            end
          end
          c.save
        end
      rescue
      end
      false
    end
  end

  def set_cached
    n = get_full_name
    update_column(:cached, n)

    # We can't use the in-memory cache approach for combination names, force reload each time
    n = nil if is_combination? 

    update_column(:cached_html, get_full_name_html(n))

    set_cached_valid_taxon_name_id

    # These two can be isolated as they are not always pertinent to a generalized cascading cache setting
    # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things
    set_cached_classified_as # why this? 
    set_cached_author_year
  end

  def set_cached_valid_taxon_name_id
    update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id)
  end

  def set_cached_warnings
    update_columns(
      cached:  NO_CACHED_MESSAGE,
      cached_author_year:  NO_CACHED_MESSAGE,
      cached_classified_as: NO_CACHED_MESSAGE,
      cached_html:  NO_CACHED_MESSAGE
    )
  end

  def set_cached_author_year
    update_column(:cached_author_year, get_author_and_year)
  end

  def set_cached_classified_as
    update_column(:cached_classified_as, get_cached_classified_as)
  end

  def get_cached_misspelling
    misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING)
    misspelling.empty? ? nil : true
  end

  # Stub, see subclasses
  # TaxonNameRelationships call it for Combinations
  def get_original_combination
    nil
  end

  # Stub, see subclasses
  #   only Protonym, but TaxonNameRelationships call it for Combinations
  def get_original_combination_html
    nil
  end

  # Returns an Array of ancestors
  #   same as self.ancestors, but also works
  #   for new records when parents specified
  def ancestors_through_parents(result = [self], start = self)
    if start.parent.nil?
      return result.reverse
    else
      result << start.parent
      ancestors_through_parents(result, start.parent)
    end
  end

  # @return [Array of TaxonName]
  #   an list of ancestors, Root first
  # Uses parent recursion when record is new and awesome_nested_set_is_not_usable
  def safe_self_and_ancestors
    if self.new_record?
      ancestors_through_parents
    else

      self.self_and_ancestors.reload.to_a.reverse ## .self_and_ancestors returns empty array!!!!!!!
    end
  end

  # @return [ [rank, prefix, name], ...] for genus and below
  # @taxon_name.full_name_array # =>  {"genus"=>[nil, "Aus"], "subgenus"=>[nil, "Aus"], "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\}
  def full_name_array
    gender = nil
    data   = []
    safe_self_and_ancestors.each do |i|
      rank   = i.rank
      gender = i.gender_name if rank == 'genus'
      method = "#{rank.gsub(/\s/, '_')}_name_elements"
      data.push([rank] + send(method, i, gender)) if self.respond_to?(method)
    end
    data
  end

  # @!return [ { rank => [prefix, name] }
  #   Returns a hash of rank => [prefix, name] for genus and below
  # @taxon_name.full_name_hash # =>
  #      {"genus" => [nil, "Aus"],
  #       "subgenus" => [nil, "Aus"],
  #       "section" => ["sect.", "Aus"],
  #       "series" => ["ser.", "Aus"],
  #       "species" => [nil, "aaa"],
  #       "subspecies" => [nil, "bbb"],
  #       "variety" => ["var.", "ccc"]}
  def full_name_hash
    gender = nil
    data   = {}
    safe_self_and_ancestors.each do |i| # !! You can not use self.self_and_ancestors because (this) record is not saved off.
      rank   = i.rank
      gender = i.gender_name if rank == 'genus'
      method = "#{rank.gsub(/\s/, '_')}_name_elements"
      #misspelling = i.cached_misspelling ? ' [sic]' : nil

      if self.respond_to?(method)
        data[rank] = send(method, i, gender)
      else
        data[rank] = i.name
      end
    end

    if data['genus'].nil?
      data['genus'] = [nil, '[GENUS NOT SPECIFIED]']
    end
    
    if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?)
      data['species'] = [nil, '[SPECIES NOT SPECIFIED]']
    end
    
    if data['variety'].nil? && !data['subvariety'].nil?
      data['variety'] = [nil, '[VARIETY NOT SPECIFIED]']
    end
    
    if data['form'].nil? && !data['subform'].nil?
      data['form'] = [nil, '[FORM NOT SPECIFIED]']
    end
    
    data
  end

  # @return [String]
  #  a monomial if names is above genus, or a full epithet if below.
  def get_full_name
    return verbatim_name if type != 'Combination' && !GENUS_AND_SPECIES_RANK_NAMES.include?(rank_string) && !verbatim_name.nil?
    return name if type != 'Combination' && !GENUS_AND_SPECIES_RANK_NAMES.include?(rank_string)
    return name if rank_class =~ /Ictv/
    return verbatim_name if !verbatim_name.nil? && type == 'Combination'
    
    d = full_name_hash
    elements = []
    elements.push(d['genus']) unless (not_binomial? && d['genus'][1] == '[GENUS NOT SPECIFIED]')
    elements.push ['(', d['subgenus'], d['section'], d['subsection'], d['series'], d['subseries'], ')']
    elements.push ['(', d['superspecies'], ')']
    elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform'])
    elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish
    elements.blank? ? nil : elements
  end 
     
  def get_full_name_html(name = nil)
    name = get_full_name if name.nil? 
    return name unless is_italicized?
    n = name 
    # n = verbatim_name.blank? ? name : verbatim_name
    return  "\"<i>Candidatus</i> #{n}\"" if is_candidatus?
    
    v = Utilities::Italicize.taxon_name(n)
    v = '' + v if is_fossil?
    v = '× ' + v if is_hybrid?
    v
  end

  def genus_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def subgenus_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def section_name_elements(*args)
    ['sect.', args[0].name_with_misspelling(args[1])]
  end

  def subsection_name_elements(*args)
    ['subsect.', args[0].name_with_misspelling(args[1])]
  end

  def series_name_elements(*args)
    ['ser.', args[0].name_with_misspelling(args[1])]
  end

  def subseries_name_elements(*args)
    ['subser.', args[0].name_with_misspelling(args[1])]
  end

  def superspecies_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def species_group_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def species_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def subspecies_name_elements(*args)
    [nil, args[0].name_with_misspelling(args[1])]
  end

  def variety_name_elements(*args)
    ['var.', args[0].name_with_misspelling(args[1])]
  end

  def subvariety_name_elements(*args)
    ['subvar.', args[0].name_with_misspelling(args[1])]
  end

  def form_name_elements(*args)
    ['f.', args[0].name_with_misspelling(args[1])]
  end

  def subform_name_elements(*args)
    ['subf.', args[0].name_with_misspelling(args[1])]
  end

  # @return [String]
  #    TODO: does this form of the name contain parens for subgenus?
  #    TODO: provide a default to gender (but do NOT eliminate param)
  #    TODO: on third thought- eliminate this mess
  def name_with_misspelling(gender)
    if cached_misspelling
      name.to_s + ' [sic]'
    elsif gender.nil? || rank_string =~ /Genus/
      name.to_s
    else
      name_in_gender(gender).to_s
    end
  end

  # @return [String, nil]
  def genderized_name(gender = nil)
    if gender.nil? || is_genus_rank?
      name
    else
      name_in_gender(gender)
    end
  end

  # return (String)
  def get_genus_species(genus_option, self_option)
  # see protonym
    true
  end

  # return [Boolean] whether there is missaplication relationship
  def name_is_missapplied?
    !TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication').empty?
  end

  # return [String]
  #   the author and year of the name, adds parenthesis where asserted
  #   abstract, see Protonym and Combination
  def get_author_and_year
    true
  end

  def icn_author_and_year
    ay = nil

    basionym = TaxonNameRelationship.where_object_is_taxon_name(self).
      with_type_string('TaxonNameRelationship::Icn::Unaccepting::Usage::Basionym')
    b_sub = basionym.empty? ? nil : basionym.first.subject_taxon_name

    misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).
      with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication')
    m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name

    t  = [self.author_string]
    t  += ['(' + self.year_integer.to_s + ')'] unless self.year_integer.nil?
    ay = t.compact.join(' ')

    unless basionym.empty? || b_sub.author_string.blank?
      ay = '(' + b_sub.author_string + ') ' + ay
    end

    unless misapplication.empty? || m_obj.author_string.blank?
      ay += ' nec ' + [m_obj.author_string]
      t  += ['(' + m_obj.year_integer.to_s + ')'] unless m_obj.year_integer.nil?
      ay = t.compact.join(' ')
    end

    ay.blank? ? nil : ay
  end

  # @return [String, nil]
  #   the authors, and year, with parentheses as inferred by the data
  def iczn_author_and_year
    ay = nil
    p = nil

    misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication')
    misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling')

    if self.type == 'Combination'
      c = protonyms_by_rank
      return nil if c.empty?
      taxon = c[c.keys.last]
    else
      taxon = self
    end

    mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name
    if !mobj.blank?
      a = [mobj.try(:author_string)]
      y = [mobj.try(:year_integer)]
    else
      a = [taxon.try(:author_string)]
      y = [taxon.try(:year_integer)]
    end

    if a[0] =~ /^\(.+\)$/ # (Author)
      a[0] = a[0][1..-2] ## remove parentheses in the author string
      p = true
    else
      p = false
    end

    ay = (a + y).compact.join(', ')

    obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name

    unless misapplication.empty? || obj.author_string.blank?
      ay += ' nec ' + ([obj.author_string] + [obj.year_integer]).compact.join(', ')
    end

    if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string)
      if p
        ay = '(' + ay + ')' unless ay.empty?
      else
        og = taxon.original_genus
        if self.type == 'Combination'
          cg = genus
        else
          cg = ancestor_at_rank('genus')
        end
        unless og.nil? || cg.nil?
          ay = '(' + ay + ')' unless ay.empty? if og.name != cg.name
        end
        #((self.original_genus.name != self.ancestor_at_rank('genus').name) && !self.original_genus.name.to_s.empty?)
      end
    end

    ay.blank? ? nil : ay
  end

  # @return [String, nil]
  def get_cached_classified_as
    return nil unless is_protonym? || is_combination?
    # source_classified_as is a method generated through relationships
    r = reload_source_classified_as
    return " (as #{r.name})" unless r.blank?
    nil
  end

  # @return [Boolean]
  def parent_is_set?
    !parent_id.nil? || (parent && parent.persisted?)
  end

  def next_sibling
    if siblings.where(project_id: project_id).load.any?
      sibs = self_and_siblings.order(:cached).pluck(:id)
      s = sibs.index(id)
      TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1
    else
      nil
    end
  end

  def previous_sibling
    if siblings.where(project_id: project_id).load.any?
      sibs = self_and_siblings.order(:cached).pluck(:id)
      s = sibs.index(id)
      TaxonName.find(sibs[s - 1]) if s != 0
    else
      nil
    end
  end

  def create_otu
    Otu.create(by: creator, project: project, taxon_name_id: id)
  end

  # @return [Scope]
  #   All taxon names attached to relationships recently created by user
  def self.used_recently_in_classifications(project_id, user_id)
    TaxonName.where(project_id: project_id)
      .joins(:taxon_name_classifications)
      .where(taxon_name_classifications: { created_at: 1.weeks.ago..Time.now } )
      .order('taxon_names.updated_at')
  end

  # @return [Scope]
  #   All taxon names attached to relationships recently created by user
  def self.used_recently_in_relationships(project_id, user_id)
    t = TaxonNameRelationship.arel_table
    t1 = t.alias('tnr1')
    t2 = t.alias('tnr2')

    sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id))
      .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id))
    ).to_sql

    sql2 = t1[:created_at].between( 1.weeks.ago..Time.now )
      .or( t2[:created_at].between( 1.weeks.ago..Time.now ) ).to_sql

    TaxonName.with_taxon_name_relationships
      .where(taxon_names: {project_id: project_id})
      .where(sql2)
      .where(sql)
      .order('taxon_names.updated_at')
  end

  # @return [Array]
  #   !! not a scope
  def self.used_recently(project_id, user_id)

    # !! If cached of one name is nill the raises an ArgumentError
    a = [
      TaxonName.touched_by(user_id).where(project_id: project_id).order(:updated_at).limit(6).to_a,
      used_recently_in_classifications(project_id, user_id).limit(6).to_a,
      used_recently_in_relationships(project_id, user_id).limit(6).to_a
    ].flatten.compact.uniq.sort{|a,b| a.cached <=> b.cached}
  end

  # @return [Hash]
  def self.select_optimized(user_id, project_id)
    h = {
      recent: TaxonName.used_recently(project_id, user_id),
      pinboard: TaxonName.pinned_by(user_id).pinned_in_project(project_id).to_a
    }

    h[:quick] = (TaxonName.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq
    h
  end

  protected

  def check_for_children
    if leaf?
      true
    else
      errors.add(:base, 'This taxon has children names attached, delete those first.')
      throw :abort
    end
  end

  def validate_parent_is_set
    if !(rank_class == NomenclaturalRank) && !(type == 'Combination')
      errors.add(:parent_id, 'is not selected') if !parent_is_set?  # parent_id.blank? && (parent.blank? || !parent.persisted?)
    end
  end

  def validate_parent_rank_is_higher
    if parent && !rank_class.blank? && rank_string != 'NomenclaturalRank'
      if RANKS.index(rank_string) <= RANKS.index(parent.rank_string)
        errors.add(:parent_id, "The parent rank (#{parent.rank_class.rank_name}) is not higher than the rank (#{rank_name}) of this taxon")
      end

      if (rank_class != rank_class_was) && children && !children.empty? && RANKS.index(rank_string) >= children.collect { |r| RANKS.index(r.rank_string).to_i }.max
        errors.add(:rank_class, "The rank of this taxon (#{rank_name}) should be higher than the ranks of children")
      end
    end
  end

  def validate_parent_from_the_same_project
    if parent && !project_id.blank?
      errors.add(:project_id, "The parent taxon is not from the same project") if project_id != parent.project_id
    end
  end

  def validate_one_root_per_project
    if new_record? || project_id_changed?
      if !parent_is_set? && TaxonName.where(parent_id: nil, project_id: project_id).count > 0
        errors.add(:parent_id, 'The parent should not be empty (only one root is allowed per project)')
      end
    end
  end

  # TODO: move to Protonym when we eliminate TaxonName.new()
  def check_new_parent_class
    if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn
      if old_parent = TaxonName.find_by(id: parent_id_was)
        if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name
          errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}")
        end
      end
    end
  end

  # See subclasses
  def validate_rank_class_class
    true
  end

  def check_new_rank_class
    # rank_class_was is a AR macro

    if (rank_class != rank_class_was) && !rank_class_was.nil?

      if rank_class_was == 'NomenclaturalRank' && rank_class_changed?
        errors.add(:rank_class, 'Root can not have a new rank')
        return
      end

      old_rank_group = rank_class_was.safe_constantize.parent
      if type == 'Protonym' && rank_class.parent != old_rank_group
        errors.add(:rank_class, "A new taxon rank (#{rank_name}) should be in the #{old_rank_group.rank_name} rank group")
      end
    end
  end

  def validate_source_type
    a = source && source.type != 'Source::Bibtex'
    b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex'
    if a || b
      errors.add(:base, 'Source must be a Bibtex')
    end
  end

  #region Soft validation

  def sv_validate_name
    correct_name_format = false

    if rank_class
      # TODO: name these Regexp somewhere
      if (name =~ /^[a-zA-Z]*$/) || # !! should reference NOT_LATIN
          (nomenclatural_code == :iczn && name =~ /^[a-zA-Z]-[a-zA-Z]*$/) ||
          (nomenclatural_code == :icnp && name =~ /^[a-zA-Z]-[a-zA-Z]*$/) ||
          (nomenclatural_code == :icn && name =~  /^[a-zA-Z]*-[a-zA-Z]*$/) ||
          (nomenclatural_code == :icn && name =~  /^[a-zA-Z]*\s×\s[a-zA-Z]*$/) ||
          (nomenclatural_code == :icn && name =~  /^×\s[a-zA-Z]*$/) ||
          (nomenclatural_code == :ictv)
        correct_name_format = true
      end

      unless correct_name_format
        invalid_statuses = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID
        invalid_statuses = invalid_statuses & taxon_name_classifications.pluck(&:type_class) # self.taxon_name_classifications.collect { |c| c.type_class.to_s }
        misspellings     = TaxonNameRelationship.collect_to_s(
          TaxonNameRelationship::Iczn::Invalidating::Usage::IncorrectOriginalSpelling,
          TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling,
          TaxonNameRelationship::Icn::Unaccepting::Usage::Misspelling)

        ictv_species = (nomenclatural_code == :ictv && self.rank_string =~ /Species/) ? true : nil
        misspellings     = misspellings & taxon_name_relationships.pluck(&:type_class) # self.taxon_name_relationships.collect { |c| c.type_class.to_s }
        if invalid_statuses.empty? && misspellings.empty? && ictv_species.nil?
          soft_validations.add(:name, 'Name should not have spaces or special characters, unless it has a status of misspelling or original misspelling')
        end
      end
    end

  end

  def sv_missing_fields
    if !self.cached_misspelling && !self.name_is_missapplied?
      if self.source.nil?
        soft_validations.add(:base, 'Original publication is not selected')
      elsif self.origin_citation.pages.nil?
        soft_validations.add(:base, 'Original citation pages are not indicated')
      elsif !self.source.pages.nil? && self.origin_citation.pages =~ /\A[0-9]+\z/
        matchdata = self.source.pages.match(/(\d+)[-–](\d+)|(\d+)/)
        minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i
        maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i
        unless (maxP && minP && minP <= self.origin_citation.pages.to_i && maxP >= self.origin_citation.pages.to_i)
          soft_validations.add(:base, 'Original citation is out of the source page range')
        end
      end
      soft_validations.add(:verbatim_author, 'Author is missing',
                           fix: :sv_fix_missing_author,
                           success_message: 'Author was updated') if self.author_string.nil? && self.type != 'Combination'
      soft_validations.add(:year_of_publication, 'Year is missing',
                           fix: :sv_fix_missing_year,
                           success_message: 'Year was updated') if self.year_integer.nil? && self.type != 'Combination'

      soft_validations.add(:etymology, 'Etymology is missing') if self.etymology.nil? && self.type != 'Combination' && self.rank_string =~ /(Genus|Species)/
    end
  end

  def sv_fix_missing_author
    if self.source
      unless self.source.author.blank?
        self.verbatim_author = self.source.authority_name
        begin
          TaxonName.transaction do
            self.save
            return true
          end
        rescue
          return false
        end
      end
    end
    false
  end

  def sv_fix_missing_year
    if self.source
      if self.source.year
        self.year_of_publication = self.source.year
        begin
          TaxonName.transaction do
            self.save
            return true
          end
        rescue
          return false
        end
      end
    end
    false
  end

  # TODO: Protonym check only?  Why can't we reference #cached_valid_taxon_name_id?
  def sv_parent_is_valid_name
    return if parent.nil?
    if parent.unavailable_or_invalid?
      # parent of a taxon is unavailable or invalid
      soft_validations.add(:parent_id, 'Parent should be a valid taxon',
                           fix:             :sv_fix_parent_is_valid_name,
                           success_message: 'Parent was updated')
    else # TODO: This seems like a different validation, split with above?
      classifications = self.taxon_name_classifications.reload
      classification_names = classifications.map { |i| i.type_name }
      compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names
      unless compare.empty?

        unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty?

          compare.each do |i|
            # taxon is unavailable or invalid, but has valid children
            soft_validations.add(:base, "Taxon has a status ('#{i.demodulize.underscore.humanize.downcase}') conflicting with presence of subordinate taxa")
          end
        end
      end
    end
  end

  def sv_fix_parent_is_valid_name
    if self.parent.unavailable_or_invalid?
      new_parent = self.parent.get_valid_taxon_name
      if self.parent != new_parent
        self.parent = new_parent
        if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies'
          self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species'
        elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus'
          self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus'
        end
        begin
          TaxonName.transaction do
            self.save
            return true
          end
        rescue
        end
      end
    end
    false
  end

  def sv_fix_cached_names
    begin
      TaxonName.transaction do
        self.save
        return true
      end
    rescue
    end
    false
  end

  # TODO: does this make sense now, with #valid_taxon_name_id in place?
  def sv_not_synonym_of_self
    if list_of_invalid_taxon_names.include?(self)
      soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.")
    end
  end

  def sv_two_unresolved_alternative_synonyms
    r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM)
    if r.to_a.size > 1
      if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date
        soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.')
      end
    end
  end

  def sv_incomplete_combination
    soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED')
    soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED')
    soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED')
    soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED')
    soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED')
    soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED')
  end

  def sv_cached_names
    true # see validation in subclasses
  end

  def sv_validate_parent_rank
    true # see validation in Protonym.rb
  end

  def sv_missing_relationships
    true # see validation in Protonym.rb
  end

  def sv_missing_classifications
    true # see validation in Protonym.rb
  end

  def sv_species_gender_agreement
    true # see validation in Protonym.rb
  end

  def sv_primary_types
    true # see validation in Protonym.rb
  end

  def sv_validate_coordinated_names
    true # see validation in Protonym.rb
  end

  def sv_type_placement
    true # see validation in Protonym.rb
  end

  def sv_single_sub_taxon
    true # see validation in Protonym.rb
  end

  def sv_parent_priority
    true # see validation in Protonym.rb
  end

  def sv_homotypic_synonyms
    true # see validation in Protonym.rb
  end

  def sv_potential_homonyms
    true # see validation in Protonym.rb
  end

  def sv_combination_duplicates
    true # see validation in Combination.rb
  end

  def sv_hybrid_name_relationships
    true # see validation in Hybrid.rb
  end

end

- (Boolean) no_cached

Returns When true cached values are not built

Returns:

  • (Boolean)

    When true cached values are not built



184
185
186
# File 'app/models/taxon_name.rb', line 184

def no_cached
  @no_cached
end

Class Method Details

+ (Hash) select_optimized(user_id, project_id)

Returns:

  • (Hash)


1123
1124
1125
1126
1127
1128
1129
1130
1131
# File 'app/models/taxon_name.rb', line 1123

def self.select_optimized(user_id, project_id)
  h = {
    recent: TaxonName.used_recently(project_id, user_id),
    pinboard: TaxonName.pinned_by(user_id).pinned_in_project(project_id).to_a
  }

  h[:quick] = (TaxonName.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq
  h
end

+ (Array of TaxonName) sort_by_rank(taxon_names)

Returns ordered by rank, a scope-like hack

Returns:

  • (Array of TaxonName)

    ordered by rank, a scope-like hack



322
323
324
# File 'app/models/taxon_name.rb', line 322

def self.sort_by_rank(taxon_names)
  taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)}
end

+ (Array) used_recently(project_id, user_id)

Returns !! not a scope

Returns:

  • (Array)

    !! not a scope



1112
1113
1114
1115
1116
1117
1118
1119
1120
# File 'app/models/taxon_name.rb', line 1112

def self.used_recently(project_id, user_id)

  # !! If cached of one name is nill the raises an ArgumentError
  a = [
    TaxonName.touched_by(user_id).where(project_id: project_id).order(:updated_at).limit(6).to_a,
    used_recently_in_classifications(project_id, user_id).limit(6).to_a,
    used_recently_in_relationships(project_id, user_id).limit(6).to_a
  ].flatten.compact.uniq.sort{|a,b| a.cached <=> b.cached}
end

+ (Scope) used_recently_in_classifications(project_id, user_id)

Returns All taxon names attached to relationships recently created by user

Returns:

  • (Scope)

    All taxon names attached to relationships recently created by user



1082
1083
1084
1085
1086
1087
# File 'app/models/taxon_name.rb', line 1082

def self.used_recently_in_classifications(project_id, user_id)
  TaxonName.where(project_id: project_id)
    .joins(:taxon_name_classifications)
    .where(taxon_name_classifications: { created_at: 1.weeks.ago..Time.now } )
    .order('taxon_names.updated_at')
end

+ (Scope) used_recently_in_relationships(project_id, user_id)

Returns All taxon names attached to relationships recently created by user

Returns:

  • (Scope)

    All taxon names attached to relationships recently created by user



1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
# File 'app/models/taxon_name.rb', line 1091

def self.used_recently_in_relationships(project_id, user_id)
  t = TaxonNameRelationship.arel_table
  t1 = t.alias('tnr1')
  t2 = t.alias('tnr2')

  sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id))
    .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id))
  ).to_sql

  sql2 = t1[:created_at].between( 1.weeks.ago..Time.now )
    .or( t2[:created_at].between( 1.weeks.ago..Time.now ) ).to_sql

  TaxonName.with_taxon_name_relationships
    .where(taxon_names: {project_id: project_id})
    .where(sql2)
    .where(sql)
    .order('taxon_names.updated_at')
end

+ (Object) with_taxon_name_relationship(relationship)



276
277
278
279
280
# File 'app/models/taxon_name.rb', line 276

def self.with_taxon_name_relationship(relationship)
  a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship})
  b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship})
  TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names")
end

Instance Method Details

- (Array) all_taxon_name_relationships

Returns all TaxonNameRelationships where this taxon is an object or subject.

Returns:

  • (Array)

    all TaxonNameRelationships where this taxon is an object or subject.



351
352
353
354
355
356
357
358
359
360
361
# File 'app/models/taxon_name.rb', line 351

def all_taxon_name_relationships
  # !! If self relationships are ever made possible this needs a DISTINCT clause
  TaxonNameRelationship.find_by_sql(
    "SELECT taxon_name_relationships.*
       FROM taxon_name_relationships
       WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id}
     UNION
     SELECT taxon_name_relationships.*
       FROM taxon_name_relationships
       WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}")
end

- (TaxonName?) ancestor_at_rank(rank)

Returns an ancestor at the specified rank

Returns:

  • (TaxonName, nil)

    an ancestor at the specified rank



490
491
492
493
494
# File 'app/models/taxon_name.rb', line 490

def ancestor_at_rank(rank)
  ancestors.with_rank_class(
    Ranks.lookup(nomenclatural_code, rank)
  ).first
end

- (Array of TaxonName) ancestor_protonyms

Returns ancestors of type 'Protonym'

Returns:

  • (Array of TaxonName)

    ancestors of type 'Protonym'



497
498
499
# File 'app/models/taxon_name.rb', line 497

def ancestor_protonyms
  Protonym.ancestors_of(self)
end

- (Object) ancestors_through_parents(result = [self], start = self)

Returns an Array of ancestors

same as self.ancestors, but also works
for new records when parents specified


745
746
747
748
749
750
751
752
# File 'app/models/taxon_name.rb', line 745

def ancestors_through_parents(result = [self], start = self)
  if start.parent.nil?
    return result.reverse
  else
    result << start.parent
    ancestors_through_parents(result, start.parent)
  end
end

- (String?) author_string

Important, string format priority is 1) as provided verbatim, 2) as generated from people, and 3) as taken from the source.

Returns:

  • (String, nil)

    the baseline means of displaying name authorship, i.e. the author for this taxon, last name only.



376
377
378
379
380
381
# File 'app/models/taxon_name.rb', line 376

def author_string
  return verbatim_author if !verbatim_author.nil?
  return Utilities::Strings.authorship_sentence( taxon_name_authors.order('roles.position').pluck(:last_name) ) if taxon_name_authors.any?
  return source.authority_name if !source.nil?
  nil
end

- (String) cached_html_name_and_author_year

Returns combination of cached_html and cached_author_year.

Returns:

  • (String)

    combination of cached_html and cached_author_year.



480
481
482
# File 'app/models/taxon_name.rb', line 480

def cached_html_name_and_author_year
  [cached_html, cached_author_year].compact.join(' ')
end

- (String) cached_name_and_author_year

Returns combination of cached and cached_author_year.

Returns:

  • (String)

    combination of cached and cached_author_year.



485
486
487
# File 'app/models/taxon_name.rb', line 485

def cached_name_and_author_year
  [cached, cached_author_year].compact.join(' ')
end

- (Object) check_for_children (protected)



1135
1136
1137
1138
1139
1140
1141
1142
# File 'app/models/taxon_name.rb', line 1135

def check_for_children
  if leaf?
    true
  else
    errors.add(:base, 'This taxon has children names attached, delete those first.')
    throw :abort
  end
end

- (Object) check_new_parent_class (protected)

TODO: move to Protonym when we eliminate TaxonName.new()



1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'app/models/taxon_name.rb', line 1177

def check_new_parent_class
  if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn
    if old_parent = TaxonName.find_by(id: parent_id_was)
      if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name
        errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}")
      end
    end
  end
end

- (Object) check_new_rank_class (protected)



1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'app/models/taxon_name.rb', line 1192

def check_new_rank_class
  # rank_class_was is a AR macro

  if (rank_class != rank_class_was) && !rank_class_was.nil?

    if rank_class_was == 'NomenclaturalRank' && rank_class_changed?
      errors.add(:rank_class, 'Root can not have a new rank')
      return
    end

    old_rank_group = rank_class_was.safe_constantize.parent
    if type == 'Protonym' && rank_class.parent != old_rank_group
      errors.add(:rank_class, "A new taxon rank (#{rank_name}) should be in the #{old_rank_group.rank_name} rank group")
    end
  end
end

- (Boolean) classification_invalid_or_unavailable?

Returns whether this name has any classification asserting that this the name is NOT valid or that it is unavailable

Returns:

  • (Boolean)

    whether this name has any classification asserting that this the name is NOT valid or that it is unavailable



520
521
522
# File 'app/models/taxon_name.rb', line 520

def classification_invalid_or_unavailable?
  taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any?
end

- (Boolean) classification_valid?

Returns true if this name has any classification asserting that it is valid

Returns:

  • (Boolean)

    true if this name has any classification asserting that it is valid



514
515
516
# File 'app/models/taxon_name.rb', line 514

def classification_valid?
  taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty?
end

- (Array of Protonym) combination_list_all

Returns all of the names this name has been in in combinations

Returns:

  • (Array of Protonym)

    all of the names this name has been in in combinations



468
469
470
# File 'app/models/taxon_name.rb', line 468

def combination_list_all
  taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq
end

- (Array of Protonym) combination_list_self

Returns for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?)

Returns:

  • (Array of Protonym)

    for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?)



474
475
476
# File 'app/models/taxon_name.rb', line 474

def combination_list_self
  combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self}
end

- (Array of String) combined_statuses

Returns the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships

Returns:

  • (Array of String)

    the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships



462
463
464
# File 'app/models/taxon_name.rb', line 462

def combined_statuses
  (statuses_from_classifications + statuses_from_relationships).uniq.sort
end

- (Object) create_new_combination_if_absent



661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'app/models/taxon_name.rb', line 661

def create_new_combination_if_absent
  return true unless type == 'Protonym'
  if !TaxonName.with_cached_html(cached_html).count == 0
    begin
      TaxonName.transaction do
        c = Combination.new
        safe_self_and_ancestors.each do |i|
          case i.rank
            when 'genus'
              c.genus = i
            when 'subgenus'
              c.subgenus = i
            when 'species'
              c.species = i
            when 'subspecies'
              c.subspecies = i
          end
        end
        c.save
      end
    rescue
    end
    false
  end
end

- (Object) create_otu



1076
1077
1078
# File 'app/models/taxon_name.rb', line 1076

def create_otu
  Otu.create(by: creator, project: project, taxon_name_id: id)
end

- (Array of TaxonName) descendant_protonyms

Returns descendants of type 'Protonym'

Returns:

  • (Array of TaxonName)

    descendants of type 'Protonym'



502
503
504
# File 'app/models/taxon_name.rb', line 502

def descendant_protonyms
  Protonym.descendants_of(self)
end

- (TaxonName) first_possible_valid_taxon_name

Returns the youngest #object_taxon_name from the youngest taxon name relationship.

Returns:

  • (TaxonName)

    returns the youngest #object_taxon_name from the youngest taxon name relationship.



598
599
600
601
602
# File 'app/models/taxon_name.rb', line 598

def first_possible_valid_taxon_name
 return self if !unavailable_or_invalid?                      # catches all cases where no Classifications or Relationships are provided
 relationship = first_possible_valid_taxon_name_relationship
 relationship.nil? ? self : relationship.object_taxon_name    # ?! probably the if is caught by unavailable_or_invalid already
end

- (TaxonNameRelationship) first_possible_valid_taxon_name_relationship

Returns youngest taxon name relationship where self is the subject.

Returns:



592
593
594
# File 'app/models/taxon_name.rb', line 592

def first_possible_valid_taxon_name_relationship
  taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation
end

- (Object) form_name_elements(*args)



904
905
906
# File 'app/models/taxon_name.rb', line 904

def form_name_elements(*args)
  ['f.', args[0].name_with_misspelling(args[1])]
end

- ([rank, prefix, name], ...) full_name_array

Returns for genus and below

Returns:

  • ([rank, prefix, name], ...)

    for genus and below



768
769
770
771
772
773
774
775
776
777
778
# File 'app/models/taxon_name.rb', line 768

def full_name_array
  gender = nil
  data   = []
  safe_self_and_ancestors.each do |i|
    rank   = i.rank
    gender = i.gender_name if rank == 'genus'
    method = "#{rank.gsub(/\s/, '_')}_name_elements"
    data.push([rank] + send(method, i, gender)) if self.respond_to?(method)
  end
  data
end

- (Object) full_name_hash



790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'app/models/taxon_name.rb', line 790

def full_name_hash
  gender = nil
  data   = {}
  safe_self_and_ancestors.each do |i| # !! You can not use self.self_and_ancestors because (this) record is not saved off.
    rank   = i.rank
    gender = i.gender_name if rank == 'genus'
    method = "#{rank.gsub(/\s/, '_')}_name_elements"
    #misspelling = i.cached_misspelling ? ' [sic]' : nil

    if self.respond_to?(method)
      data[rank] = send(method, i, gender)
    else
      data[rank] = i.name
    end
  end

  if data['genus'].nil?
    data['genus'] = [nil, '[GENUS NOT SPECIFIED]']
  end
  
  if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?)
    data['species'] = [nil, '[SPECIES NOT SPECIFIED]']
  end
  
  if data['variety'].nil? && !data['subvariety'].nil?
    data['variety'] = [nil, '[VARIETY NOT SPECIFIED]']
  end
  
  if data['form'].nil? && !data['subform'].nil?
    data['form'] = [nil, '[FORM NOT SPECIFIED]']
  end
  
  data
end

- (Object) gbif_status_array



630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'app/models/taxon_name.rb', line 630

def gbif_status_array
  return nil if self.class.nil?
  return ['combination'] if self.class == 'Combination'
  s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact
  return s1 unless s1.empty?
  s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject}
  s3 = related_taxon_name_relationships.collect{|r| r.class.gbif_status_of_object}

  s = s2 + s3
  s.compact!
  return ['valid'] if s.empty?
  s
end

- (Class?) gender_class

Returns gender of a genus as class

Returns:

  • (Class, nil)

    gender of a genus as class



409
410
411
# File 'app/models/taxon_name.rb', line 409

def gender_class
  gender_instance.try(:type_class)
end

- (TaxonNameClassification instance?) gender_instance

Returns the gender classification of this name, if provided

Returns:



415
416
417
# File 'app/models/taxon_name.rb', line 415

def gender_instance
  taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first
end

- (String?) gender_name

Returns gender as a string (only applicable to Genera)

Returns:

  • (String, nil)

    gender as a string (only applicable to Genera)



421
422
423
# File 'app/models/taxon_name.rb', line 421

def gender_name
  gender_instance.try(:classification_label).try(:downcase)
end

- (String?) genderized_name(gender = nil)

Returns:

  • (String, nil)


927
928
929
930
931
932
933
# File 'app/models/taxon_name.rb', line 927

def genderized_name(gender = nil)
  if gender.nil? || is_genus_rank?
    name
  else
    name_in_gender(gender)
  end
end

- (Object) genus_name_elements(*args)



856
857
858
# File 'app/models/taxon_name.rb', line 856

def genus_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Object) get_author_and_year

return [String]

the author and year of the name, adds parenthesis where asserted
abstract, see Protonym and Combination


949
950
951
# File 'app/models/taxon_name.rb', line 949

def get_author_and_year
  true
end

- (String?) get_cached_classified_as

Returns:

  • (String, nil)


1043
1044
1045
1046
1047
1048
1049
# File 'app/models/taxon_name.rb', line 1043

def get_cached_classified_as
  return nil unless is_protonym? || is_combination?
  # source_classified_as is a method generated through relationships
  r = reload_source_classified_as
  return " (as #{r.name})" unless r.blank?
  nil
end

- (Object) get_cached_misspelling



725
726
727
728
# File 'app/models/taxon_name.rb', line 725

def get_cached_misspelling
  misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING)
  misspelling.empty? ? nil : true
end

- (String) get_full_name

Returns a monomial if names is above genus, or a full epithet if below.

Returns:

  • (String)

    a monomial if names is above genus, or a full epithet if below.



827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'app/models/taxon_name.rb', line 827

def get_full_name
  return verbatim_name if type != 'Combination' && !GENUS_AND_SPECIES_RANK_NAMES.include?(rank_string) && !verbatim_name.nil?
  return name if type != 'Combination' && !GENUS_AND_SPECIES_RANK_NAMES.include?(rank_string)
  return name if rank_class =~ /Ictv/
  return verbatim_name if !verbatim_name.nil? && type == 'Combination'
  
  d = full_name_hash
  elements = []
  elements.push(d['genus']) unless (not_binomial? && d['genus'][1] == '[GENUS NOT SPECIFIED]')
  elements.push ['(', d['subgenus'], d['section'], d['subsection'], d['series'], d['subseries'], ')']
  elements.push ['(', d['superspecies'], ')']
  elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform'])
  elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish
  elements.blank? ? nil : elements
end

- (Object) get_full_name_html(name = nil)



843
844
845
846
847
848
849
850
851
852
853
854
# File 'app/models/taxon_name.rb', line 843

def get_full_name_html(name = nil)
  name = get_full_name if name.nil? 
  return name unless is_italicized?
  n = name 
  # n = verbatim_name.blank? ? name : verbatim_name
  return  "\"<i>Candidatus</i> #{n}\"" if is_candidatus?
  
  v = Utilities::Italicize.taxon_name(n)
  v = '' + v if is_fossil?
  v = '× ' + v if is_hybrid?
  v
end

- (Object) get_genus_species(genus_option, self_option)

return (String)



936
937
938
939
# File 'app/models/taxon_name.rb', line 936

def get_genus_species(genus_option, self_option)
# see protonym
  true
end

- (Object) get_original_combination

Stub, see subclasses TaxonNameRelationships call it for Combinations



732
733
734
# File 'app/models/taxon_name.rb', line 732

def get_original_combination
  nil
end

- (Object) get_original_combination_html

Stub, see subclasses

only Protonym, but TaxonNameRelationships call it for Combinations


738
739
740
# File 'app/models/taxon_name.rb', line 738

def get_original_combination_html
  nil
end

- (TaxonName) get_valid_taxon_name

Returns a valid taxon_name for an invalid name or self for valid name. a stub here - See Protonym and Combination

Returns:

  • (TaxonName)

    a valid taxon_name for an invalid name or self for valid name. a stub here - See Protonym and Combination



586
587
588
# File 'app/models/taxon_name.rb', line 586

def get_valid_taxon_name
  nil
end

- (Object) icn_author_and_year



953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'app/models/taxon_name.rb', line 953

def icn_author_and_year
  ay = nil

  basionym = TaxonNameRelationship.where_object_is_taxon_name(self).
    with_type_string('TaxonNameRelationship::Icn::Unaccepting::Usage::Basionym')
  b_sub = basionym.empty? ? nil : basionym.first.subject_taxon_name

  misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).
    with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication')
  m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name

  t  = [self.author_string]
  t  += ['(' + self.year_integer.to_s + ')'] unless self.year_integer.nil?
  ay = t.compact.join(' ')

  unless basionym.empty? || b_sub.author_string.blank?
    ay = '(' + b_sub.author_string + ') ' + ay
  end

  unless misapplication.empty? || m_obj.author_string.blank?
    ay += ' nec ' + [m_obj.author_string]
    t  += ['(' + m_obj.year_integer.to_s + ')'] unless m_obj.year_integer.nil?
    ay = t.compact.join(' ')
  end

  ay.blank? ? nil : ay
end

- (String?) iczn_author_and_year

Returns the authors, and year, with parentheses as inferred by the data

Returns:

  • (String, nil)

    the authors, and year, with parentheses as inferred by the data



983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# File 'app/models/taxon_name.rb', line 983

def iczn_author_and_year
  ay = nil
  p = nil

  misapplication = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication')
  misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling')

  if self.type == 'Combination'
    c = protonyms_by_rank
    return nil if c.empty?
    taxon = c[c.keys.last]
  else
    taxon = self
  end

  mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name
  if !mobj.blank?
    a = [mobj.try(:author_string)]
    y = [mobj.try(:year_integer)]
  else
    a = [taxon.try(:author_string)]
    y = [taxon.try(:year_integer)]
  end

  if a[0] =~ /^\(.+\)$/ # (Author)
    a[0] = a[0][1..-2] ## remove parentheses in the author string
    p = true
  else
    p = false
  end

  ay = (a + y).compact.join(', ')

  obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name

  unless misapplication.empty? || obj.author_string.blank?
    ay += ' nec ' + ([obj.author_string] + [obj.year_integer]).compact.join(', ')
  end

  if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string)
    if p
      ay = '(' + ay + ')' unless ay.empty?
    else
      og = taxon.original_genus
      if self.type == 'Combination'
        cg = genus
      else
        cg = ancestor_at_rank('genus')
      end
      unless og.nil? || cg.nil?
        ay = '(' + ay + ')' unless ay.empty? if og.name != cg.name
      end
      #((self.original_genus.name != self.ancestor_at_rank('genus').name) && !self.original_genus.name.to_s.empty?)
    end
  end

  ay.blank? ? nil : ay
end

- (True|False) is_candidatus?

Returns true if this name has a TaxonNameClassification of candidatus

Returns:

  • (True|False)

    true if this name has a TaxonNameClassification of candidatus



566
567
568
569
# File 'app/models/taxon_name.rb', line 566

def is_candidatus?
  return false unless rank_string =~ /Icnp/
  taxon_name_classifications.where_taxon_name(self).with_type_contains('Candidatus').any?
end

- (Boolean) is_combination?

Returns:

  • (Boolean)


548
549
550
# File 'app/models/taxon_name.rb', line 548

def is_combination?
  type == 'Combination'
end

- (True|False) is_fossil?

Returns true if this name has a TaxonNameClassification of Fossil

Returns:

  • (True|False)

    true if this name has a TaxonNameClassification of Fossil



554
555
556
# File 'app/models/taxon_name.rb', line 554

def is_fossil?
  taxon_name_classifications.with_type_contains('::Fossil').any?
end

- (Boolean) is_genus_or_species_rank?

Returns see subclasses

Returns:

  • (Boolean)

    see subclasses



579
580
581
# File 'app/models/taxon_name.rb', line 579

def is_genus_or_species_rank?
  false
end

- (Boolean) is_hybrid?

Returns true if this name has a TaxonNameClassification of hybrid

Returns:

  • (Boolean)

    true if this name has a TaxonNameClassification of hybrid



560
561
562
# File 'app/models/taxon_name.rb', line 560

def is_hybrid?
  taxon_name_classifications.where_taxon_name(self).with_type_contains('Hybrid').any?
end

- (Boolean) is_italicized?

Returns whether this name needs italics applied

Returns:

  • (Boolean)

    whether this name needs italics applied



540
541
542
# File 'app/models/taxon_name.rb', line 540

def is_italicized?
  is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) 
end

- (Boolean) is_protonym?

Returns:

  • (Boolean)


544
545
546
# File 'app/models/taxon_name.rb', line 544

def is_protonym?
  type == 'Protonym'
end

- (Boolean) is_valid?

Returns after all inference on the validity of a name, the result is stored in cached_valid_taxon_name_id, #is_valid checks that result

Returns:

  • (Boolean)

    after all inference on the validity of a name, the result is stored in cached_valid_taxon_name_id, #is_valid checks that result



534
535
536
# File 'app/models/taxon_name.rb', line 534

def is_valid?
  id == cached_valid_taxon_name_id
end

- (Array of TaxonName) list_of_invalid_taxon_names

TODO: Can't we just use #valid_id now?

Returns:

  • (Array of TaxonName)

    returns list of invalid names for a given taxon.



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'app/models/taxon_name.rb', line 607

def list_of_invalid_taxon_names
  first_pass = true
  list = {}
  while first_pass || !list.keys.select{|t| list[t] == false}.empty? do
    first_pass = false
    list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false}
    list_of_taxa_to_check.each do |t|
      potentialy_invalid_relationships = t.related_taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first
      potentialy_invalid_relationships.find_each do |r|
        if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty?
          # do nothing, taxon has a status of valid name
        elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship
          list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil?
        end

      end
      list[t] = true if list[t] == false
    end
  end
  return [] if list.empty?
  list.sort_by{|t, a| (t.nomenclature_date || Time.now)}.collect{|t, a| t}
end

- (Array of Strings) name_in_gender(gender = nil)

Returns names of all genera where the species was placed

Returns:

  • (Array of Strings)

    names of all genera where the species was placed



646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'app/models/taxon_name.rb', line 646

def name_in_gender(gender = nil)
  case gender
    when 'masculine'
      n = masculine_name
    when 'feminine'
      n = feminine_name
    when 'neuter'
      n = neuter_name
    else
      n = nil
  end
  n = n.blank? ? name : n
  return n
end

- (Boolean) name_is_missapplied?

return [Boolean] whether there is missaplication relationship

Returns:

  • (Boolean)


942
943
944
# File 'app/models/taxon_name.rb', line 942

def name_is_missapplied?
  !TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication').empty?
end

- (String) name_with_misspelling(gender)

Returns TODO: does this form of the name contain parens for subgenus? TODO: provide a default to gender (but do NOT eliminate param) TODO: on third thought- eliminate this mess

Returns:

  • (String)

    TODO: does this form of the name contain parens for subgenus? TODO: provide a default to gender (but do NOT eliminate param) TODO: on third thought- eliminate this mess



916
917
918
919
920
921
922
923
924
# File 'app/models/taxon_name.rb', line 916

def name_with_misspelling(gender)
  if cached_misspelling
    name.to_s + ' [sic]'
  elsif gender.nil? || rank_string =~ /Genus/
    name.to_s
  else
    name_in_gender(gender).to_s
  end
end

- (Object) next_sibling



1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'app/models/taxon_name.rb', line 1056

def next_sibling
  if siblings.where(project_id: project_id).load.any?
    sibs = self_and_siblings.order(:cached).pluck(:id)
    s = sibs.index(id)
    TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1
  else
    nil
  end
end

- (Time) nomenclature_date

Returns effective date of publication, used to determine nomenclatural priority

Returns:

  • (Time)

    effective date of publication, used to determine nomenclatural priority



392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'app/models/taxon_name.rb', line 392

def nomenclature_date
  return nil if self.id.nil?
   family_before_1961 = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_string('TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961').first

  # family_before_1961 = taxon_name_relationships.with_type_string('TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961').first
  if family_before_1961.nil?
    year = self.year_of_publication ? Time.utc(self.year_of_publication, 12, 31) : nil
    self.source ? (self.source.cached_nomenclature_date ? self.source.nomenclature_date : year) : year
  else
    obj  = family_before_1961.object_taxon_name
    year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil
    obj.source ? (self.source.cached_nomenclature_date ? obj.source.nomenclature_date : year) : year
  end
end

- (True|False) not_binomial?

Returns true if this name has a TaxonNameClassification of not_binomial

Returns:

  • (True|False)

    true if this name has a TaxonNameClassification of not_binomial



573
574
575
# File 'app/models/taxon_name.rb', line 573

def not_binomial?
  taxon_name_classifications.where_taxon_name(self).with_type_contains('NonBinomial').any?
end

- (Boolean) parent_is_set?

Returns:

  • (Boolean)


1052
1053
1054
# File 'app/models/taxon_name.rb', line 1052

def parent_is_set?
  !parent_id.nil? || (parent && parent.persisted?)
end

- (Class) part_of_speech_class

Returns part of speech of a species as class.

Returns:

  • (Class)

    part of speech of a species as class.



427
428
429
# File 'app/models/taxon_name.rb', line 427

def part_of_speech_class
  part_of_speech_instance.try(:type_class)
end

- (Object) part_of_speech_instance



431
432
433
# File 'app/models/taxon_name.rb', line 431

def part_of_speech_instance
  taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first
end

- (String) part_of_speech_name

Returns part of speech of a species as string.

Returns:

  • (String)

    part of speech of a species as string.



437
438
439
# File 'app/models/taxon_name.rb', line 437

def part_of_speech_name
  part_of_speech_instance.try(:classification_label).try(:downcase)
end

- (Object) previous_sibling



1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'app/models/taxon_name.rb', line 1066

def previous_sibling
  if siblings.where(project_id: project_id).load.any?
    sibs = self_and_siblings.order(:cached).pluck(:id)
    s = sibs.index(id)
    TaxonName.find(sibs[s - 1]) if s != 0
  else
    nil
  end
end

- (String) rank

Returns rank as human readable shortform, like 'genus' or 'species'

Returns:

  • (String)

    rank as human readable shortform, like 'genus' or 'species'



328
329
330
# File 'app/models/taxon_name.rb', line 328

def rank
  ::RANKS.include?(rank_string) ? rank_name : nil
end

- (NomenclaturalRank class) rank_class



344
345
346
347
# File 'app/models/taxon_name.rb', line 344

def rank_class
  r = read_attribute(:rank_class)
  Ranks.valid?(r) ? r.safe_constantize : r
end

- (Object) rank_class=(value)



338
339
340
# File 'app/models/taxon_name.rb', line 338

def rank_class=(value)
  write_attribute(:rank_class, value.to_s)
end

- (String) rank_string

Returns rank (Kindom, Phylum…) as a string, like NomenclaturalRank::Iczn::SpeciesGroup::Species

Returns:



334
335
336
# File 'app/models/taxon_name.rb', line 334

def rank_string
  read_attribute(:rank_class)
end

Returns all taxon_names which have relationships to this taxon as an object or subject.

Returns:

  • (Array of TaxonName)

    all taxon_names which have relationships to this taxon as an object or subject.



365
366
367
368
369
370
371
# File 'app/models/taxon_name.rb', line 365

def related_taxon_names
  TaxonName.find_by_sql(
    "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id}
    UNION
    SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}"
  )
end

- (Boolean) relationship_invalid?

Returns true if there is a relationship where then name is asserted to be invalid

Returns:

  • (Boolean)

    true if there is a relationship where then name is asserted to be invalid



508
509
510
# File 'app/models/taxon_name.rb', line 508

def relationship_invalid?
  !first_possible_valid_taxon_name_relationship.nil?
end

- (Array of TaxonName) safe_self_and_ancestors

Uses parent recursion when record is new and awesome_nested_set_is_not_usable

Returns:

  • (Array of TaxonName)

    an list of ancestors, Root first



757
758
759
760
761
762
763
764
# File 'app/models/taxon_name.rb', line 757

def safe_self_and_ancestors
  if self.new_record?
    ancestors_through_parents
  else

    self.self_and_ancestors.reload.to_a.reverse ## .self_and_ancestors returns empty array!!!!!!!
  end
end

- (Object) section_name_elements(*args)



864
865
866
# File 'app/models/taxon_name.rb', line 864

def section_name_elements(*args)
  ['sect.', args[0].name_with_misspelling(args[1])]
end

- (Object) series_name_elements(*args)



872
873
874
# File 'app/models/taxon_name.rb', line 872

def series_name_elements(*args)
  ['ser.', args[0].name_with_misspelling(args[1])]
end

- (Object) set_cached



687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# File 'app/models/taxon_name.rb', line 687

def set_cached
  n = get_full_name
  update_column(:cached, n)

  # We can't use the in-memory cache approach for combination names, force reload each time
  n = nil if is_combination? 

  update_column(:cached_html, get_full_name_html(n))

  set_cached_valid_taxon_name_id

  # These two can be isolated as they are not always pertinent to a generalized cascading cache setting
  # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things
  set_cached_classified_as # why this? 
  set_cached_author_year
end

- (Object) set_cached_author_year



717
718
719
# File 'app/models/taxon_name.rb', line 717

def set_cached_author_year
  update_column(:cached_author_year, get_author_and_year)
end

- (Object) set_cached_classified_as



721
722
723
# File 'app/models/taxon_name.rb', line 721

def set_cached_classified_as
  update_column(:cached_classified_as, get_cached_classified_as)
end

- (Object) set_cached_valid_taxon_name_id



704
705
706
# File 'app/models/taxon_name.rb', line 704

def set_cached_valid_taxon_name_id
  update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id)
end

- (Object) set_cached_warnings



708
709
710
711
712
713
714
715
# File 'app/models/taxon_name.rb', line 708

def set_cached_warnings
  update_columns(
    cached:  NO_CACHED_MESSAGE,
    cached_author_year:  NO_CACHED_MESSAGE,
    cached_classified_as: NO_CACHED_MESSAGE,
    cached_html:  NO_CACHED_MESSAGE
  )
end

- (Object) species_group_name_elements(*args)



884
885
886
# File 'app/models/taxon_name.rb', line 884

def species_group_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Object) species_name_elements(*args)



888
889
890
# File 'app/models/taxon_name.rb', line 888

def species_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Array of String) statuses_from_classifications

Returns the unique string labels derived from TaxonNameClassifications

Returns:

  • (Array of String)

    the unique string labels derived from TaxonNameClassifications



443
444
445
446
# File 'app/models/taxon_name.rb', line 443

def statuses_from_classifications
  list = taxon_name_classifications_for_statuses
  list.empty? ? [] : list.collect{|c| c.classification_label }.sort
end

- (Array of String) statuses_from_relationships

Returns the unique string labels derived from and TaxonNameRelationships

Returns:

  • (Array of String)

    the unique string labels derived from and TaxonNameRelationships



455
456
457
458
# File 'app/models/taxon_name.rb', line 455

def statuses_from_relationships
  list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES)
  list.empty? ? [] : list.collect{|c| c.subject_status}.sort
end

- (Object) subform_name_elements(*args)



908
909
910
# File 'app/models/taxon_name.rb', line 908

def subform_name_elements(*args)
  ['subf.', args[0].name_with_misspelling(args[1])]
end

- (Object) subgenus_name_elements(*args)



860
861
862
# File 'app/models/taxon_name.rb', line 860

def subgenus_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Object) subsection_name_elements(*args)



868
869
870
# File 'app/models/taxon_name.rb', line 868

def subsection_name_elements(*args)
  ['subsect.', args[0].name_with_misspelling(args[1])]
end

- (Object) subseries_name_elements(*args)



876
877
878
# File 'app/models/taxon_name.rb', line 876

def subseries_name_elements(*args)
  ['subser.', args[0].name_with_misspelling(args[1])]
end

- (Object) subspecies_name_elements(*args)



892
893
894
# File 'app/models/taxon_name.rb', line 892

def subspecies_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Object) subvariety_name_elements(*args)



900
901
902
# File 'app/models/taxon_name.rb', line 900

def subvariety_name_elements(*args)
  ['subvar.', args[0].name_with_misspelling(args[1])]
end

- (Object) superspecies_name_elements(*args)



880
881
882
# File 'app/models/taxon_name.rb', line 880

def superspecies_name_elements(*args)
  [nil, args[0].name_with_misspelling(args[1])]
end

- (Object) sv_cached_names (protected)



1394
1395
1396
# File 'app/models/taxon_name.rb', line 1394

def sv_cached_names
  true # see validation in subclasses
end

- (Object) sv_combination_duplicates (protected)



1442
1443
1444
# File 'app/models/taxon_name.rb', line 1442

def sv_combination_duplicates
  true # see validation in Combination.rb
end

- (Object) sv_fix_cached_names (protected)



1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
# File 'app/models/taxon_name.rb', line 1358

def sv_fix_cached_names
  begin
    TaxonName.transaction do
      self.save
      return true
    end
  rescue
  end
  false
end

- (Object) sv_fix_missing_author (protected)



1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
# File 'app/models/taxon_name.rb', line 1277

def sv_fix_missing_author
  if self.source
    unless self.source.author.blank?
      self.verbatim_author = self.source.authority_name
      begin
        TaxonName.transaction do
          self.save
          return true
        end
      rescue
        return false
      end
    end
  end
  false
end

- (Object) sv_fix_missing_year (protected)



1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
# File 'app/models/taxon_name.rb', line 1294

def sv_fix_missing_year
  if self.source
    if self.source.year
      self.year_of_publication = self.source.year
      begin
        TaxonName.transaction do
          self.save
          return true
        end
      rescue
        return false
      end
    end
  end
  false
end

- (Object) sv_fix_parent_is_valid_name (protected)



1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'app/models/taxon_name.rb', line 1336

def sv_fix_parent_is_valid_name
  if self.parent.unavailable_or_invalid?
    new_parent = self.parent.get_valid_taxon_name
    if self.parent != new_parent
      self.parent = new_parent
      if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies'
        self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species'
      elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus'
        self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus'
      end
      begin
        TaxonName.transaction do
          self.save
          return true
        end
      rescue
      end
    end
  end
  false
end

- (Object) sv_homotypic_synonyms (protected)



1434
1435
1436
# File 'app/models/taxon_name.rb', line 1434

def sv_homotypic_synonyms
  true # see validation in Protonym.rb
end

- (Object) sv_hybrid_name_relationships (protected)



1446
1447
1448
# File 'app/models/taxon_name.rb', line 1446

def sv_hybrid_name_relationships
  true # see validation in Hybrid.rb
end

- (Object) sv_incomplete_combination (protected)



1385
1386
1387
1388
1389
1390
1391
1392
# File 'app/models/taxon_name.rb', line 1385

def sv_incomplete_combination
  soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED')
  soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED')
  soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED')
  soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED')
  soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED')
  soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED')
end

- (Object) sv_missing_classifications (protected)



1406
1407
1408
# File 'app/models/taxon_name.rb', line 1406

def sv_missing_classifications
  true # see validation in Protonym.rb
end

- (Object) sv_missing_fields (protected)



1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
# File 'app/models/taxon_name.rb', line 1252

def sv_missing_fields
  if !self.cached_misspelling && !self.name_is_missapplied?
    if self.source.nil?
      soft_validations.add(:base, 'Original publication is not selected')
    elsif self.origin_citation.pages.nil?
      soft_validations.add(:base, 'Original citation pages are not indicated')
    elsif !self.source.pages.nil? && self.origin_citation.pages =~ /\A[0-9]+\z/
      matchdata = self.source.pages.match(/(\d+)[-–](\d+)|(\d+)/)
      minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i
      maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i
      unless (maxP && minP && minP <= self.origin_citation.pages.to_i && maxP >= self.origin_citation.pages.to_i)
        soft_validations.add(:base, 'Original citation is out of the source page range')
      end
    end
    soft_validations.add(:verbatim_author, 'Author is missing',
                         fix: :sv_fix_missing_author,
                         success_message: 'Author was updated') if self.author_string.nil? && self.type != 'Combination'
    soft_validations.add(:year_of_publication, 'Year is missing',
                         fix: :sv_fix_missing_year,
                         success_message: 'Year was updated') if self.year_integer.nil? && self.type != 'Combination'

    soft_validations.add(:etymology, 'Etymology is missing') if self.etymology.nil? && self.type != 'Combination' && self.rank_string =~ /(Genus|Species)/
  end
end

- (Object) sv_missing_relationships (protected)



1402
1403
1404
# File 'app/models/taxon_name.rb', line 1402

def sv_missing_relationships
  true # see validation in Protonym.rb
end

- (Object) sv_not_synonym_of_self (protected)

TODO: does this make sense now, with #valid_taxon_name_id in place?



1370
1371
1372
1373
1374
# File 'app/models/taxon_name.rb', line 1370

def sv_not_synonym_of_self
  if list_of_invalid_taxon_names.include?(self)
    soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.")
  end
end

- (Object) sv_parent_is_valid_name (protected)

TODO: Protonym check only? Why can't we reference #cached_valid_taxon_name_id?



1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'app/models/taxon_name.rb', line 1312

def sv_parent_is_valid_name
  return if parent.nil?
  if parent.unavailable_or_invalid?
    # parent of a taxon is unavailable or invalid
    soft_validations.add(:parent_id, 'Parent should be a valid taxon',
                         fix:             :sv_fix_parent_is_valid_name,
                         success_message: 'Parent was updated')
  else # TODO: This seems like a different validation, split with above?
    classifications = self.taxon_name_classifications.reload
    classification_names = classifications.map { |i| i.type_name }
    compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names
    unless compare.empty?

      unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty?

        compare.each do |i|
          # taxon is unavailable or invalid, but has valid children
          soft_validations.add(:base, "Taxon has a status ('#{i.demodulize.underscore.humanize.downcase}') conflicting with presence of subordinate taxa")
        end
      end
    end
  end
end

- (Object) sv_parent_priority (protected)



1430
1431
1432
# File 'app/models/taxon_name.rb', line 1430

def sv_parent_priority
  true # see validation in Protonym.rb
end

- (Object) sv_potential_homonyms (protected)



1438
1439
1440
# File 'app/models/taxon_name.rb', line 1438

def sv_potential_homonyms
  true # see validation in Protonym.rb
end

- (Object) sv_primary_types (protected)



1414
1415
1416
# File 'app/models/taxon_name.rb', line 1414

def sv_primary_types
  true # see validation in Protonym.rb
end

- (Object) sv_single_sub_taxon (protected)



1426
1427
1428
# File 'app/models/taxon_name.rb', line 1426

def sv_single_sub_taxon
  true # see validation in Protonym.rb
end

- (Object) sv_species_gender_agreement (protected)



1410
1411
1412
# File 'app/models/taxon_name.rb', line 1410

def sv_species_gender_agreement
  true # see validation in Protonym.rb
end

- (Object) sv_two_unresolved_alternative_synonyms (protected)



1376
1377
1378
1379
1380
1381
1382
1383
# File 'app/models/taxon_name.rb', line 1376

def sv_two_unresolved_alternative_synonyms
  r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM)
  if r.to_a.size > 1
    if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date
      soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.')
    end
  end
end

- (Object) sv_type_placement (protected)



1422
1423
1424
# File 'app/models/taxon_name.rb', line 1422

def sv_type_placement
  true # see validation in Protonym.rb
end

- (Object) sv_validate_coordinated_names (protected)



1418
1419
1420
# File 'app/models/taxon_name.rb', line 1418

def sv_validate_coordinated_names
  true # see validation in Protonym.rb
end

- (Object) sv_validate_name (protected)

region Soft validation



1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
# File 'app/models/taxon_name.rb', line 1219

def sv_validate_name
  correct_name_format = false

  if rank_class
    # TODO: name these Regexp somewhere
    if (name =~ /^[a-zA-Z]*$/) || # !! should reference NOT_LATIN
        (nomenclatural_code == :iczn && name =~ /^[a-zA-Z]-[a-zA-Z]*$/) ||
        (nomenclatural_code == :icnp && name =~ /^[a-zA-Z]-[a-zA-Z]*$/) ||
        (nomenclatural_code == :icn && name =~  /^[a-zA-Z]*-[a-zA-Z]*$/) ||
        (nomenclatural_code == :icn && name =~  /^[a-zA-Z]*\s×\s[a-zA-Z]*$/) ||
        (nomenclatural_code == :icn && name =~  /^×\s[a-zA-Z]*$/) ||
        (nomenclatural_code == :ictv)
      correct_name_format = true
    end

    unless correct_name_format
      invalid_statuses = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID
      invalid_statuses = invalid_statuses & taxon_name_classifications.pluck(&:type_class) # self.taxon_name_classifications.collect { |c| c.type_class.to_s }
      misspellings     = TaxonNameRelationship.collect_to_s(
        TaxonNameRelationship::Iczn::Invalidating::Usage::IncorrectOriginalSpelling,
        TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling,
        TaxonNameRelationship::Icn::Unaccepting::Usage::Misspelling)

      ictv_species = (nomenclatural_code == :ictv && self.rank_string =~ /Species/) ? true : nil
      misspellings     = misspellings & taxon_name_relationships.pluck(&:type_class) # self.taxon_name_relationships.collect { |c| c.type_class.to_s }
      if invalid_statuses.empty? && misspellings.empty? && ictv_species.nil?
        soft_validations.add(:name, 'Name should not have spaces or special characters, unless it has a status of misspelling or original misspelling')
      end
    end
  end

end

- (Object) sv_validate_parent_rank (protected)



1398
1399
1400
# File 'app/models/taxon_name.rb', line 1398

def sv_validate_parent_rank
  true # see validation in Protonym.rb
end

- (Scope) synonyms

Returns Protonym(s) the **broad sense** synonyms of this name

Returns:

  • (Scope)

    Protonym(s) the **broad sense** synonyms of this name



308
309
310
# File 'app/models/taxon_name.rb', line 308

def synonyms
  TaxonName.with_cached_valid_taxon_name_id(self.id)
end

- (Scope) taxon_name_classifications_for_statuses

Returns:

  • (Scope)


449
450
451
# File 'app/models/taxon_name.rb', line 449

def taxon_name_classifications_for_statuses
  taxon_name_classifications.with_type_array(ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNB_TAXON_NAME_CLASSIFICATION_NAMES + ICTV_TAXON_NAME_CLASSIFICATION_NAMES)
end

- (Boolean) unavailable_or_invalid?

@return [Boolean]

return true if name is unavailable OR invalid, else false, checks both classifications and relationships

Returns:

  • (Boolean)


526
527
528
529
# File 'app/models/taxon_name.rb', line 526

def unavailable_or_invalid?
  return false if classification_valid?
  classification_invalid_or_unavailable? || relationship_invalid?
end

- (Object) validate_one_root_per_project (protected)



1168
1169
1170
1171
1172
1173
1174
# File 'app/models/taxon_name.rb', line 1168

def validate_one_root_per_project
  if new_record? || project_id_changed?
    if !parent_is_set? && TaxonName.where(parent_id: nil, project_id: project_id).count > 0
      errors.add(:parent_id, 'The parent should not be empty (only one root is allowed per project)')
    end
  end
end

- (Object) validate_parent_from_the_same_project (protected)



1162
1163
1164
1165
1166
# File 'app/models/taxon_name.rb', line 1162

def validate_parent_from_the_same_project
  if parent && !project_id.blank?
    errors.add(:project_id, "The parent taxon is not from the same project") if project_id != parent.project_id
  end
end

- (Object) validate_parent_is_set (protected)



1144
1145
1146
1147
1148
# File 'app/models/taxon_name.rb', line 1144

def validate_parent_is_set
  if !(rank_class == NomenclaturalRank) && !(type == 'Combination')
    errors.add(:parent_id, 'is not selected') if !parent_is_set?  # parent_id.blank? && (parent.blank? || !parent.persisted?)
  end
end

- (Object) validate_parent_rank_is_higher (protected)



1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'app/models/taxon_name.rb', line 1150

def validate_parent_rank_is_higher
  if parent && !rank_class.blank? && rank_string != 'NomenclaturalRank'
    if RANKS.index(rank_string) <= RANKS.index(parent.rank_string)
      errors.add(:parent_id, "The parent rank (#{parent.rank_class.rank_name}) is not higher than the rank (#{rank_name}) of this taxon")
    end

    if (rank_class != rank_class_was) && children && !children.empty? && RANKS.index(rank_string) >= children.collect { |r| RANKS.index(r.rank_string).to_i }.max
      errors.add(:rank_class, "The rank of this taxon (#{rank_name}) should be higher than the ranks of children")
    end
  end
end

- (Object) validate_rank_class_class (protected)

See subclasses



1188
1189
1190
# File 'app/models/taxon_name.rb', line 1188

def validate_rank_class_class
  true
end

- (Object) validate_source_type (protected)



1209
1210
1211
1212
1213
1214
1215
# File 'app/models/taxon_name.rb', line 1209

def validate_source_type
  a = source && source.type != 'Source::Bibtex'
  b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex'
  if a || b
    errors.add(:base, 'Source must be a Bibtex')
  end
end

- (Object) variety_name_elements(*args)



896
897
898
# File 'app/models/taxon_name.rb', line 896

def variety_name_elements(*args)
  ['var.', args[0].name_with_misspelling(args[1])]
end

- (Integer) year_integer

Returns a 4 digit integer representing year of publication, like 1974

Returns:

  • (Integer)

    a 4 digit integer representing year of publication, like 1974



385
386
387
388
# File 'app/models/taxon_name.rb', line 385

def year_integer
  return year_of_publication if !year_of_publication.nil?
  try(:source).try(:year)
end