Class: FHIR::Model

Inherits:
Object
  • Object
show all
Extended by:
Deprecate
Defined in:
lib/fhir_models/bootstrap/model.rb

Direct Known Subclasses

Account, Account::Coverage, Account::Guarantor, ActivityDefinition, ActivityDefinition::DynamicValue, ActivityDefinition::Participant, Address, AdverseEvent, AdverseEvent::SuspectEntity, AdverseEvent::SuspectEntity::Causality, Age, AllergyIntolerance, AllergyIntolerance::Reaction, Annotation, Appointment, Appointment::Participant, AppointmentResponse, Attachment, AuditEvent, AuditEvent::Agent, AuditEvent::Agent::Network, AuditEvent::Entity, AuditEvent::Entity::Detail, AuditEvent::Source, BackboneElement, Basic, Binary, BiologicallyDerivedProduct, BiologicallyDerivedProduct::Collection, BiologicallyDerivedProduct::Manipulation, BiologicallyDerivedProduct::Processing, BiologicallyDerivedProduct::Storage, BodyStructure, Bundle, Bundle::Entry, Bundle::Entry::Request, Bundle::Entry::Response, Bundle::Entry::Search, Bundle::Link, CapabilityStatement, CapabilityStatement::Document, CapabilityStatement::Implementation, CapabilityStatement::Messaging, CapabilityStatement::Messaging::Endpoint, CapabilityStatement::Messaging::SupportedMessage, CapabilityStatement::Rest, CapabilityStatement::Rest::Interaction, CapabilityStatement::Rest::Resource, CapabilityStatement::Rest::Resource::Interaction, CapabilityStatement::Rest::Resource::Operation, CapabilityStatement::Rest::Resource::SearchParam, CapabilityStatement::Rest::Security, CapabilityStatement::Software, CarePlan, CarePlan::Activity, CarePlan::Activity::Detail, CareTeam, CareTeam::Participant, CatalogEntry, CatalogEntry::RelatedEntry, ChargeItem, ChargeItem::Performer, ChargeItemDefinition, ChargeItemDefinition::Applicability, ChargeItemDefinition::PropertyGroup, ChargeItemDefinition::PropertyGroup::PriceComponent, Claim, Claim::Accident, Claim::CareTeam, Claim::Diagnosis, Claim::Insurance, Claim::Item, Claim::Item::Detail, Claim::Item::Detail::SubDetail, Claim::Payee, Claim::Procedure, Claim::Related, Claim::SupportingInfo, ClaimResponse, ClaimResponse::AddItem, ClaimResponse::AddItem::Detail, ClaimResponse::AddItem::Detail::SubDetail, ClaimResponse::Error, ClaimResponse::Insurance, ClaimResponse::Item, ClaimResponse::Item::Adjudication, ClaimResponse::Item::Detail, ClaimResponse::Item::Detail::SubDetail, ClaimResponse::Payment, ClaimResponse::ProcessNote, ClaimResponse::Total, ClinicalImpression, ClinicalImpression::Finding, ClinicalImpression::Investigation, CodeSystem, CodeSystem::Concept, CodeSystem::Concept::Designation, CodeSystem::Concept::Property, CodeSystem::Filter, CodeSystem::Property, CodeableConcept, Coding, Communication, Communication::Payload, CommunicationRequest, CommunicationRequest::Payload, CompartmentDefinition, CompartmentDefinition::Resource, Composition, Composition::Attester, Composition::Event, Composition::RelatesTo, Composition::Section, ConceptMap, ConceptMap::Group, ConceptMap::Group::Element, ConceptMap::Group::Element::Target, ConceptMap::Group::Element::Target::DependsOn, ConceptMap::Group::Unmapped, Condition, Condition::Evidence, Condition::Stage, Consent, Consent::Policy, Consent::Provision, Consent::Provision::Actor, Consent::Provision::Data, Consent::Verification, ContactDetail, ContactPoint, Contract, Contract::ContentDefinition, Contract::Friendly, Contract::Legal, Contract::Rule, Contract::Signer, Contract::Term, Contract::Term::Action, Contract::Term::Action::Subject, Contract::Term::Asset, Contract::Term::Asset::Context, Contract::Term::Asset::ValuedItem, Contract::Term::Offer, Contract::Term::Offer::Answer, Contract::Term::Offer::Party, Contract::Term::SecurityLabel, Contributor, Count, Coverage, Coverage::Class, Coverage::CostToBeneficiary, Coverage::CostToBeneficiary::Exception, CoverageEligibilityRequest, CoverageEligibilityRequest::Insurance, CoverageEligibilityRequest::Item, CoverageEligibilityRequest::Item::Diagnosis, CoverageEligibilityRequest::SupportingInfo, CoverageEligibilityResponse, CoverageEligibilityResponse::Error, CoverageEligibilityResponse::Insurance, CoverageEligibilityResponse::Insurance::Item, CoverageEligibilityResponse::Insurance::Item::Benefit, DataRequirement, DataRequirement::CodeFilter, DataRequirement::DateFilter, DataRequirement::Sort, DetectedIssue, DetectedIssue::Evidence, DetectedIssue::Mitigation, Device, Device::DeviceName, Device::Property, Device::Specialization, Device::UdiCarrier, Device::Version, DeviceDefinition, DeviceDefinition::Capability, DeviceDefinition::DeviceName, DeviceDefinition::Material, DeviceDefinition::Property, DeviceDefinition::Specialization, DeviceDefinition::UdiDeviceIdentifier, DeviceMetric, DeviceMetric::Calibration, DeviceRequest, DeviceRequest::Parameter, DeviceUseStatement, DiagnosticReport, DiagnosticReport::Media, Distance, DocumentManifest, DocumentManifest::Related, DocumentReference, DocumentReference::Content, DocumentReference::Context, DocumentReference::RelatesTo, DomainResource, Dosage, Dosage::DoseAndRate, Duration, EffectEvidenceSynthesis, EffectEvidenceSynthesis::Certainty, EffectEvidenceSynthesis::Certainty::CertaintySubcomponent, EffectEvidenceSynthesis::EffectEstimate, EffectEvidenceSynthesis::EffectEstimate::PrecisionEstimate, EffectEvidenceSynthesis::ResultsByExposure, EffectEvidenceSynthesis::SampleSize, Element, ElementDefinition, ElementDefinition::Base, ElementDefinition::Binding, ElementDefinition::Constraint, ElementDefinition::Example, ElementDefinition::Mapping, ElementDefinition::Slicing, ElementDefinition::Slicing::Discriminator, ElementDefinition::Type, Encounter, Encounter::ClassHistory, Encounter::Diagnosis, Encounter::Hospitalization, Encounter::Location, Encounter::Participant, Encounter::StatusHistory, Endpoint, EnrollmentRequest, EnrollmentResponse, EpisodeOfCare, EpisodeOfCare::Diagnosis, EpisodeOfCare::StatusHistory, EventDefinition, Evidence, EvidenceVariable, EvidenceVariable::Characteristic, ExampleScenario, ExampleScenario::Actor, ExampleScenario::Instance, ExampleScenario::Instance::ContainedInstance, ExampleScenario::Instance::Version, ExampleScenario::Process, ExampleScenario::Process::Step, ExampleScenario::Process::Step::Alternative, ExampleScenario::Process::Step::Operation, ExplanationOfBenefit, ExplanationOfBenefit::Accident, ExplanationOfBenefit::AddItem, ExplanationOfBenefit::AddItem::Detail, ExplanationOfBenefit::AddItem::Detail::SubDetail, ExplanationOfBenefit::BenefitBalance, ExplanationOfBenefit::BenefitBalance::Financial, ExplanationOfBenefit::CareTeam, ExplanationOfBenefit::Diagnosis, ExplanationOfBenefit::Insurance, ExplanationOfBenefit::Item, ExplanationOfBenefit::Item::Adjudication, ExplanationOfBenefit::Item::Detail, ExplanationOfBenefit::Item::Detail::SubDetail, ExplanationOfBenefit::Payee, ExplanationOfBenefit::Payment, ExplanationOfBenefit::Procedure, ExplanationOfBenefit::ProcessNote, ExplanationOfBenefit::Related, ExplanationOfBenefit::SupportingInfo, ExplanationOfBenefit::Total, Expression, Extension, FamilyMemberHistory, FamilyMemberHistory::Condition, Flag, Goal, Goal::Target, GraphDefinition, GraphDefinition::Link, GraphDefinition::Link::Target, GraphDefinition::Link::Target::Compartment, Group, Group::Characteristic, Group::Member, GuidanceResponse, HealthcareService, HealthcareService::AvailableTime, HealthcareService::Eligibility, HealthcareService::NotAvailable, HumanName, Identifier, ImagingStudy, ImagingStudy::Series, ImagingStudy::Series::Instance, ImagingStudy::Series::Performer, Immunization, Immunization::Education, Immunization::Performer, Immunization::ProtocolApplied, Immunization::Reaction, ImmunizationEvaluation, ImmunizationRecommendation, ImmunizationRecommendation::Recommendation, ImmunizationRecommendation::Recommendation::DateCriterion, ImplementationGuide, ImplementationGuide::Definition, ImplementationGuide::Definition::Grouping, ImplementationGuide::Definition::Page, ImplementationGuide::Definition::Parameter, ImplementationGuide::Definition::Resource, ImplementationGuide::Definition::Template, ImplementationGuide::DependsOn, ImplementationGuide::Global, ImplementationGuide::Manifest, ImplementationGuide::Manifest::Page, ImplementationGuide::Manifest::Resource, InsurancePlan, InsurancePlan::Contact, InsurancePlan::Coverage, InsurancePlan::Coverage::Benefit, InsurancePlan::Coverage::Benefit::Limit, InsurancePlan::Plan, InsurancePlan::Plan::GeneralCost, InsurancePlan::Plan::SpecificCost, InsurancePlan::Plan::SpecificCost::Benefit, InsurancePlan::Plan::SpecificCost::Benefit::Cost, Invoice, Invoice::LineItem, Invoice::LineItem::PriceComponent, Invoice::Participant, Library, Linkage, Linkage::Item, List, List::Entry, Location, Location::HoursOfOperation, Location::Position, MarketingStatus, Measure, FHIR::Measure::Group, FHIR::Measure::Group::Population, FHIR::Measure::Group::Stratifier, FHIR::Measure::Group::Stratifier::Component, FHIR::Measure::SupplementalData, MeasureReport, FHIR::MeasureReport::Group, FHIR::MeasureReport::Group::Population, FHIR::MeasureReport::Group::Stratifier, FHIR::MeasureReport::Group::Stratifier::Stratum, FHIR::MeasureReport::Group::Stratifier::Stratum::Component, FHIR::MeasureReport::Group::Stratifier::Stratum::Population, Media, Medication, FHIR::Medication::Batch, FHIR::Medication::Ingredient, MedicationAdministration, FHIR::MedicationAdministration::Dosage, FHIR::MedicationAdministration::Performer, MedicationDispense, FHIR::MedicationDispense::Performer, FHIR::MedicationDispense::Substitution, MedicationKnowledge, FHIR::MedicationKnowledge::AdministrationGuidelines, FHIR::MedicationKnowledge::AdministrationGuidelines::Dosage, FHIR::MedicationKnowledge::AdministrationGuidelines::PatientCharacteristics, FHIR::MedicationKnowledge::Cost, FHIR::MedicationKnowledge::DrugCharacteristic, FHIR::MedicationKnowledge::Ingredient, FHIR::MedicationKnowledge::Kinetics, FHIR::MedicationKnowledge::MedicineClassification, FHIR::MedicationKnowledge::MonitoringProgram, FHIR::MedicationKnowledge::Monograph, FHIR::MedicationKnowledge::Packaging, FHIR::MedicationKnowledge::Regulatory, FHIR::MedicationKnowledge::Regulatory::MaxDispense, FHIR::MedicationKnowledge::Regulatory::Schedule, FHIR::MedicationKnowledge::Regulatory::Substitution, FHIR::MedicationKnowledge::RelatedMedicationKnowledge, MedicationRequest, FHIR::MedicationRequest::DispenseRequest, FHIR::MedicationRequest::DispenseRequest::InitialFill, FHIR::MedicationRequest::Substitution, MedicationStatement, MedicinalProduct, FHIR::MedicinalProduct::ManufacturingBusinessOperation, FHIR::MedicinalProduct::Name, FHIR::MedicinalProduct::Name::CountryLanguage, FHIR::MedicinalProduct::Name::NamePart, FHIR::MedicinalProduct::SpecialDesignation, MedicinalProductAuthorization, FHIR::MedicinalProductAuthorization::JurisdictionalAuthorization, FHIR::MedicinalProductAuthorization::Procedure, MedicinalProductContraindication, FHIR::MedicinalProductContraindication::OtherTherapy, MedicinalProductIndication, FHIR::MedicinalProductIndication::OtherTherapy, MedicinalProductIngredient, FHIR::MedicinalProductIngredient::SpecifiedSubstance, FHIR::MedicinalProductIngredient::SpecifiedSubstance::Strength, FHIR::MedicinalProductIngredient::SpecifiedSubstance::Strength::ReferenceStrength, FHIR::MedicinalProductIngredient::Substance, MedicinalProductInteraction, FHIR::MedicinalProductInteraction::Interactant, MedicinalProductManufactured, MedicinalProductPackaged, FHIR::MedicinalProductPackaged::BatchIdentifier, FHIR::MedicinalProductPackaged::PackageItem, MedicinalProductPharmaceutical, FHIR::MedicinalProductPharmaceutical::Characteristics, FHIR::MedicinalProductPharmaceutical::RouteOfAdministration, FHIR::MedicinalProductPharmaceutical::RouteOfAdministration::TargetSpecies, FHIR::MedicinalProductPharmaceutical::RouteOfAdministration::TargetSpecies::WithdrawalPeriod, MedicinalProductUndesirableEffect, MessageDefinition, FHIR::MessageDefinition::AllowedResponse, FHIR::MessageDefinition::Focus, MessageHeader, FHIR::MessageHeader::Destination, FHIR::MessageHeader::Response, FHIR::MessageHeader::Source, Meta, MolecularSequence, FHIR::MolecularSequence::Quality, FHIR::MolecularSequence::Quality::Roc, FHIR::MolecularSequence::ReferenceSeq, FHIR::MolecularSequence::Repository, FHIR::MolecularSequence::StructureVariant, FHIR::MolecularSequence::StructureVariant::Inner, FHIR::MolecularSequence::StructureVariant::Outer, FHIR::MolecularSequence::Variant, Money, NamingSystem, NamingSystem::UniqueId, Narrative, NutritionOrder, NutritionOrder::EnteralFormula, NutritionOrder::EnteralFormula::Administration, NutritionOrder::OralDiet, NutritionOrder::OralDiet::Nutrient, NutritionOrder::OralDiet::Texture, NutritionOrder::Supplement, Observation, Observation::Component, Observation::ReferenceRange, ObservationDefinition, ObservationDefinition::QualifiedInterval, ObservationDefinition::QuantitativeDetails, OperationDefinition, OperationDefinition::Overload, OperationDefinition::Parameter, OperationDefinition::Parameter::Binding, OperationDefinition::Parameter::ReferencedFrom, OperationOutcome, OperationOutcome::Issue, Organization, Organization::Contact, OrganizationAffiliation, ParameterDefinition, Parameters, Parameters::Parameter, Patient, Patient::Communication, Patient::Contact, Patient::Link, PaymentNotice, PaymentReconciliation, PaymentReconciliation::Detail, PaymentReconciliation::ProcessNote, Period, Person, Person::Link, PlanDefinition, PlanDefinition::Action, PlanDefinition::Action::Condition, PlanDefinition::Action::DynamicValue, PlanDefinition::Action::Participant, PlanDefinition::Action::RelatedAction, PlanDefinition::Goal, PlanDefinition::Goal::Target, Population, Practitioner, Practitioner::Qualification, PractitionerRole, PractitionerRole::AvailableTime, PractitionerRole::NotAvailable, Procedure, Procedure::FocalDevice, Procedure::Performer, ProdCharacteristic, ProductShelfLife, Provenance, Provenance::Agent, Provenance::Entity, Quantity, Questionnaire, Questionnaire::Item, Questionnaire::Item::AnswerOption, Questionnaire::Item::EnableWhen, Questionnaire::Item::Initial, QuestionnaireResponse, QuestionnaireResponse::Item, QuestionnaireResponse::Item::Answer, Range, Ratio, Reference, RelatedArtifact, RelatedPerson, RelatedPerson::Communication, RequestGroup, RequestGroup::Action, RequestGroup::Action::Condition, RequestGroup::Action::RelatedAction, ResearchDefinition, ResearchElementDefinition, ResearchElementDefinition::Characteristic, ResearchStudy, ResearchStudy::Arm, ResearchStudy::Objective, ResearchSubject, Resource, RiskAssessment, RiskAssessment::Prediction, RiskEvidenceSynthesis, RiskEvidenceSynthesis::Certainty, RiskEvidenceSynthesis::Certainty::CertaintySubcomponent, RiskEvidenceSynthesis::RiskEstimate, RiskEvidenceSynthesis::RiskEstimate::PrecisionEstimate, RiskEvidenceSynthesis::SampleSize, SampledData, Schedule, SearchParameter, SearchParameter::Component, ServiceRequest, Signature, Slot, Specimen, Specimen::Collection, Specimen::Container, Specimen::Processing, SpecimenDefinition, SpecimenDefinition::TypeTested, SpecimenDefinition::TypeTested::Container, SpecimenDefinition::TypeTested::Container::Additive, SpecimenDefinition::TypeTested::Handling, StructureDefinition, StructureDefinition::Context, StructureDefinition::Differential, StructureDefinition::Mapping, StructureDefinition::Snapshot, StructureMap, StructureMap::Group, StructureMap::Group::Input, StructureMap::Group::Rule, StructureMap::Group::Rule::Dependent, StructureMap::Group::Rule::Source, StructureMap::Group::Rule::Target, StructureMap::Group::Rule::Target::Parameter, StructureMap::Structure, Subscription, Subscription::Channel, Substance, Substance::Ingredient, Substance::Instance, SubstanceAmount, SubstanceAmount::ReferenceRange, SubstanceNucleicAcid, SubstanceNucleicAcid::Subunit, SubstanceNucleicAcid::Subunit::Linkage, SubstanceNucleicAcid::Subunit::Sugar, SubstancePolymer, SubstancePolymer::MonomerSet, SubstancePolymer::MonomerSet::StartingMaterial, SubstancePolymer::Repeat, SubstancePolymer::Repeat::RepeatUnit, SubstancePolymer::Repeat::RepeatUnit::DegreeOfPolymerisation, SubstancePolymer::Repeat::RepeatUnit::StructuralRepresentation, SubstanceProtein, SubstanceProtein::Subunit, SubstanceReferenceInformation, SubstanceReferenceInformation::Classification, SubstanceReferenceInformation::Gene, SubstanceReferenceInformation::GeneElement, SubstanceReferenceInformation::Target, SubstanceSourceMaterial, SubstanceSourceMaterial::FractionDescription, SubstanceSourceMaterial::Organism, SubstanceSourceMaterial::Organism::Author, SubstanceSourceMaterial::Organism::Hybrid, SubstanceSourceMaterial::Organism::OrganismGeneral, SubstanceSourceMaterial::PartDescription, SubstanceSpecification, SubstanceSpecification::Code, SubstanceSpecification::Moiety, SubstanceSpecification::Name, SubstanceSpecification::Name::Official, SubstanceSpecification::Property, SubstanceSpecification::Relationship, SubstanceSpecification::Structure, SubstanceSpecification::Structure::Isotope, SubstanceSpecification::Structure::Isotope::MolecularWeight, SubstanceSpecification::Structure::Representation, SupplyDelivery, SupplyDelivery::SuppliedItem, SupplyRequest, SupplyRequest::Parameter, Task, Task::Input, Task::Output, Task::Restriction, TerminologyCapabilities, TerminologyCapabilities::Closure, TerminologyCapabilities::CodeSystem, TerminologyCapabilities::CodeSystem::Version, TerminologyCapabilities::CodeSystem::Version::Filter, TerminologyCapabilities::Expansion, TerminologyCapabilities::Expansion::Parameter, TerminologyCapabilities::Implementation, TerminologyCapabilities::Software, TerminologyCapabilities::Translation, TerminologyCapabilities::ValidateCode, TestReport, TestReport::Participant, TestReport::Setup, TestReport::Setup::Action, TestReport::Setup::Action::Assert, TestReport::Setup::Action::Operation, TestReport::Teardown, TestReport::Teardown::Action, TestReport::Test, TestReport::Test::Action, TestScript, TestScript::Destination, TestScript::Fixture, TestScript::Metadata, TestScript::Metadata::Capability, TestScript::Metadata::Link, TestScript::Origin, TestScript::Setup, TestScript::Setup::Action, TestScript::Setup::Action::Assert, TestScript::Setup::Action::Operation, TestScript::Setup::Action::Operation::RequestHeader, TestScript::Teardown, TestScript::Teardown::Action, TestScript::Test, TestScript::Test::Action, TestScript::Variable, Timing, Timing::Repeat, TriggerDefinition, UsageContext, ValueSet, ValueSet::Compose, ValueSet::Compose::Include, ValueSet::Compose::Include::Concept, ValueSet::Compose::Include::Concept::Designation, ValueSet::Compose::Include::Filter, ValueSet::Expansion, ValueSet::Expansion::Contains, ValueSet::Expansion::Parameter, VerificationResult, VerificationResult::Attestation, VerificationResult::PrimarySource, VerificationResult::Validator, VisionPrescription, VisionPrescription::LensSpecification, VisionPrescription::LensSpecification::Prism

Instance Method Summary collapse

Methods included from Deprecate

deprecate

Constructor Details

#initialize(hash = {}) ⇒ Model

Returns a new instance of Model.



9
10
11
12
13
14
15
16
17
18
# File 'lib/fhir_models/bootstrap/model.rb', line 9

def initialize(hash = {})
  from_hash(hash)
  self.class::METADATA.each do |key, value|
    local_name = key
    local_name = value['local_name'] if value['local_name']
    if value['max'] > 1 && instance_variable_get("@#{local_name}").nil?
      instance_variable_set("@#{local_name}".to_sym, [])
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *_args, &_block) ⇒ Object

Raises:

  • (NoMethodError)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/fhir_models/bootstrap/model.rb', line 31

def method_missing(method, *_args, &_block)
  if defined?(self.class::MULTIPLE_TYPES) && self.class::MULTIPLE_TYPES[method.to_s]
    self.class::MULTIPLE_TYPES[method.to_s].each do |type|
      type[0] = type[0].upcase
      value = send("#{method}#{type}".to_sym)
      return value unless value.nil?
    end
    return nil
  elsif !@extension.nil? && !@extension.empty?
    ext = @extension.select do |x|
      name = x.url.tr('-', '_').split('/').last
      anchor = name.split('#').last
      (method.to_s == name || method.to_s == anchor)
    end
    unless ext.first.nil?
      return ext.first.value.nil? ? ext.first : ext.first.value
    end
  elsif !@modifierExtension.nil? && !@modifierExtension.empty?
    ext = @modifierExtension.select do |x|
      name = x.url.tr('-', '_').split('/').last
      anchor = name.split('#').last
      (method.to_s == name || method.to_s == anchor)
    end
    unless ext.first.nil?
      return ext.first.value.nil? ? ext.first : ext.first.value
    end
  end
  raise NoMethodError.new("undefined method `#{method}' for #{inspect}", method)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

allow two FHIR models to be compared for equality



26
27
28
# File 'lib/fhir_models/bootstrap/model.rb', line 26

def ==(other)
  self.class == other.class && to_hash == other.to_hash
end

#attribute_mismatch(left, right, exclude = []) ⇒ Object



84
85
86
87
88
89
90
# File 'lib/fhir_models/bootstrap/model.rb', line 84

def attribute_mismatch(left, right, exclude = [])
  if left.respond_to?(:mismatch) && right.respond_to?(:mismatch)
    left.mismatch right, exclude
  else
    compare_attribute(left, right, exclude)
  end
end

#compare_attribute(left, right, exclude = []) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/fhir_models/bootstrap/model.rb', line 92

def compare_attribute(left, right, exclude = [])
  if left.respond_to?(:equals?) && right.respond_to?(:equals?)
    left.equals? right, exclude
  elsif left.is_a?(Array) && right.is_a?(Array) && (left.length == right.length)
    result = true
    (0...(left.length)).each { |i| result &&= compare_attribute(left[i], right[i], exclude) }
    result
  else
    left == right
  end
end

#equals?(other, exclude = []) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
68
69
70
# File 'lib/fhir_models/bootstrap/model.rb', line 65

def equals?(other, exclude = [])
  (self.class::METADATA.keys - exclude).each do |attribute|
    return false unless compare_attribute(instance_variable_get("@#{attribute}".to_sym), other.instance_variable_get("@#{attribute}".to_sym), exclude)
  end
  true
end

#hashObject

This is necessary for uniq to properly identify two FHIR models as being identical



21
22
23
# File 'lib/fhir_models/bootstrap/model.rb', line 21

def hash
  to_hash.hash
end

#mismatch(other, exclude = []) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/fhir_models/bootstrap/model.rb', line 72

def mismatch(other, exclude = [])
  misses = []
  (self.class::METADATA.keys - exclude).each do |key|
    these = attribute_mismatch(instance_variable_get("@#{key}".to_sym), other.instance_variable_get("@#{key}".to_sym), exclude)
    if !these || (these.is_a?(Array) && !these.empty?)
      misses << "#{self.class}::#{key}"
      misses.concat these if these.is_a?(Array)
    end
  end
  misses
end

#primitive?(datatype, value) ⇒ Boolean

Returns:

  • (Boolean)


274
275
276
277
# File 'lib/fhir_models/bootstrap/model.rb', line 274

def primitive?(datatype, value)
  FHIR.logger.warn("prefer using FHIR.primitive? Called from #{caller.first}")
  FHIR.primitive?(datatype: datatype, value: value)
end

#to_referenceObject



61
62
63
# File 'lib/fhir_models/bootstrap/model.rb', line 61

def to_reference
  FHIR::Reference.new(reference: "#{self.class.name.split('::').last}/#{id}")
end

#valid?Boolean

Returns:

  • (Boolean)


104
105
106
# File 'lib/fhir_models/bootstrap/model.rb', line 104

def valid?
  validate.empty?
end

#validate(contained = nil) ⇒ Object



109
110
111
# File 'lib/fhir_models/bootstrap/model.rb', line 109

def validate(contained = nil)
  validate_profile(self.class::METADATA, contained)
end

#validate_profile(metadata, contained = nil) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/fhir_models/bootstrap/model.rb', line 113

def validate_profile(, contained = nil)
  contained_here = [instance_variable_get('@contained'.to_sym)].flatten
  contained_here << contained
  contained_here = contained_here.flatten.compact
  errors = {}
  .each do |field, meta|
    if meta.is_a?(Array)
      # this field has been 'sliced'
      meta.each do |slice|
        local_name = slice['local_name'] || field
        value = [instance_variable_get("@#{local_name}".to_sym)].flatten.compact
        subset = [] # subset is the values associated with just this slice
        if slice['type'] == 'Extension'
          subset = if slice['type_profiles']
                     value.select { |x| slice['type_profiles'].include?(x.url) }
                   else
                     value
                   end
        else
          FHIR.logger.warn 'Validation not supported on slices (except for Extensions)'
        end
        validate_field(field, subset, contained_here, slice, errors)
      end
    else
      local_name = meta['local_name'] || field
      value = [instance_variable_get("@#{local_name}".to_sym)].flatten.compact
      validate_field(field, value, contained_here, meta, errors)
    end
  end # metadata.each
  # check multiple types
  multiple_types = begin
                     self.class::MULTIPLE_TYPES
                   rescue
                     {}
                   end
  multiple_types.each do |prefix, suffixes|
    present = []
    suffixes.each do |suffix|
      typename = "#{prefix}#{suffix[0].upcase}#{suffix[1..-1]}"
      # check which multiple data types are actually present, not just errors
      # actually, this might be allowed depending on cardinality
      value = instance_variable_get("@#{typename}")
      present << typename if !value.nil? || (value.is_a?(Array) && !value.empty?)
    end
    errors[prefix] = ["#{prefix}[x]: more than one type present."] if present.length > 1
    # remove errors for suffixes that are not present
    next unless present.length == 1
    suffixes.each do |suffix|
      typename = "#{prefix}#{suffix[0].upcase}#{suffix[1..-1]}"
      errors.delete(typename) unless present.include?(typename)
    end
  end
  errors.keep_if { |_k, v| (v && !v.empty?) }
end