Class: FHIR::DSTU2::Model

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

Direct Known Subclasses

Account, Address, AllergyIntolerance, AllergyIntolerance::Reaction, Annotation, Appointment, Appointment::Participant, AppointmentResponse, Attachment, AuditEvent, AuditEvent::Event, AuditEvent::Object, AuditEvent::Object::Detail, AuditEvent::Participant, AuditEvent::Participant::Network, AuditEvent::Source, BackboneElement, Basic, Binary, BodySite, Bundle, Bundle::Entry, Bundle::Entry::Request, Bundle::Entry::Response, Bundle::Entry::Search, Bundle::Link, CarePlan, CarePlan::Activity, CarePlan::Activity::Detail, CarePlan::Participant, CarePlan::RelatedPlan, Claim, Claim::Coverage, Claim::Diagnosis, Claim::Item, Claim::Item::Detail, Claim::Item::Detail::SubDetail, Claim::Item::Prosthesis, Claim::MissingTeeth, Claim::Payee, ClaimResponse, ClaimResponse::AddItem, ClaimResponse::AddItem::Adjudication, ClaimResponse::AddItem::Detail, ClaimResponse::AddItem::Detail::Adjudication, ClaimResponse::Coverage, ClaimResponse::Error, ClaimResponse::Item, ClaimResponse::Item::Adjudication, ClaimResponse::Item::Detail, ClaimResponse::Item::Detail::Adjudication, ClaimResponse::Item::Detail::SubDetail, ClaimResponse::Item::Detail::SubDetail::Adjudication, ClaimResponse::Item::Detail::Subadjudication, ClaimResponse::Note, ClinicalImpression, ClinicalImpression::Finding, ClinicalImpression::Investigations, ClinicalImpression::RuledOut, CodeableConcept, Coding, Communication, Communication::Payload, CommunicationRequest, CommunicationRequest::Payload, Composition, Composition::Attester, Composition::Event, Composition::Section, ConceptMap, ConceptMap::Contact, ConceptMap::Element, ConceptMap::Element::Target, ConceptMap::Element::Target::DependsOn, Condition, Condition::Evidence, Condition::Stage, Conformance, Conformance::Contact, Conformance::Document, Conformance::Implementation, Conformance::Messaging, Conformance::Messaging::Endpoint, Conformance::Messaging::Event, Conformance::Rest, Conformance::Rest::Interaction, Conformance::Rest::Operation, Conformance::Rest::Resource, Conformance::Rest::Resource::Interaction, Conformance::Rest::Resource::SearchParam, Conformance::Rest::Security, Conformance::Rest::Security::Certificate, Conformance::Software, ContactPoint, Contract, Contract::Actor, Contract::Friendly, Contract::Legal, Contract::Rule, Contract::Signer, Contract::Term, Contract::Term::Actor, Contract::Term::ValuedItem, Contract::ValuedItem, Coverage, DataElement, DataElement::Contact, DataElement::Mapping, DetectedIssue, DetectedIssue::Mitigation, Device, DeviceComponent, DeviceComponent::ProductionSpecification, DeviceMetric, DeviceMetric::Calibration, DeviceUseRequest, DeviceUseStatement, DiagnosticOrder, DiagnosticOrder::Event, DiagnosticOrder::Item, DiagnosticReport, DiagnosticReport::Image, DocumentManifest, DocumentManifest::Content, DocumentManifest::Related, DocumentReference, DocumentReference::Content, DocumentReference::Context, DocumentReference::Context::Related, DocumentReference::RelatesTo, DomainResource, Element, ElementDefinition, ElementDefinition::Base, ElementDefinition::Binding, ElementDefinition::Constraint, ElementDefinition::Mapping, ElementDefinition::Slicing, ElementDefinition::Type, EligibilityRequest, EligibilityResponse, Encounter, Encounter::Hospitalization, Encounter::Location, Encounter::Participant, Encounter::StatusHistory, EnrollmentRequest, EnrollmentResponse, EpisodeOfCare, EpisodeOfCare::CareTeam, EpisodeOfCare::StatusHistory, ExplanationOfBenefit, Extension, FamilyMemberHistory, FamilyMemberHistory::Condition, Flag, Goal, Goal::Outcome, Group, Group::Characteristic, Group::Member, HealthcareService, HealthcareService::AvailableTime, HealthcareService::NotAvailable, HealthcareService::ServiceType, HumanName, Identifier, ImagingObjectSelection, ImagingObjectSelection::Study, ImagingObjectSelection::Study::Series, ImagingObjectSelection::Study::Series::Instance, ImagingObjectSelection::Study::Series::Instance::Frames, ImagingStudy, ImagingStudy::Series, ImagingStudy::Series::Instance, Immunization, Immunization::Explanation, Immunization::Reaction, Immunization::VaccinationProtocol, ImmunizationRecommendation, ImmunizationRecommendation::Recommendation, ImmunizationRecommendation::Recommendation::DateCriterion, ImmunizationRecommendation::Recommendation::Protocol, ImplementationGuide, ImplementationGuide::Contact, ImplementationGuide::Dependency, ImplementationGuide::Global, ImplementationGuide::Package, ImplementationGuide::Package::Resource, ImplementationGuide::Page, List, List::Entry, Location, Location::Position, Media, Medication, FHIR::DSTU2::Medication::Package, FHIR::DSTU2::Medication::Package::Content, FHIR::DSTU2::Medication::Product, FHIR::DSTU2::Medication::Product::Batch, FHIR::DSTU2::Medication::Product::Ingredient, MedicationAdministration, FHIR::DSTU2::MedicationAdministration::Dosage, MedicationDispense, FHIR::DSTU2::MedicationDispense::DosageInstruction, FHIR::DSTU2::MedicationDispense::Substitution, MedicationOrder, FHIR::DSTU2::MedicationOrder::DispenseRequest, FHIR::DSTU2::MedicationOrder::DosageInstruction, FHIR::DSTU2::MedicationOrder::Substitution, MedicationStatement, FHIR::DSTU2::MedicationStatement::Dosage, MessageHeader, FHIR::DSTU2::MessageHeader::Destination, FHIR::DSTU2::MessageHeader::Response, FHIR::DSTU2::MessageHeader::Source, Meta, NamingSystem, NamingSystem::Contact, NamingSystem::UniqueId, Narrative, NutritionOrder, NutritionOrder::EnteralFormula, NutritionOrder::EnteralFormula::Administration, NutritionOrder::OralDiet, NutritionOrder::OralDiet::Nutrient, NutritionOrder::OralDiet::Texture, NutritionOrder::Supplement, Observation, Observation::Component, Observation::ReferenceRange, Observation::Related, OperationDefinition, OperationDefinition::Contact, OperationDefinition::Parameter, OperationDefinition::Parameter::Binding, OperationOutcome, OperationOutcome::Issue, Order, Order::When, OrderResponse, Organization, Organization::Contact, Parameters, Parameters::Parameter, Patient, Patient::Animal, Patient::Communication, Patient::Contact, Patient::Link, PaymentNotice, PaymentReconciliation, PaymentReconciliation::Detail, PaymentReconciliation::Note, Period, Person, Person::Link, Practitioner, Practitioner::PractitionerRole, Practitioner::Qualification, Procedure, Procedure::FocalDevice, Procedure::Performer, ProcedureRequest, ProcessRequest, ProcessRequest::Item, ProcessResponse, ProcessResponse::Notes, Provenance, Provenance::Agent, Provenance::Agent::RelatedAgent, Provenance::Entity, Quantity, Questionnaire, Questionnaire::Group, Questionnaire::Group::Question, QuestionnaireResponse, QuestionnaireResponse::Group, QuestionnaireResponse::Group::Question, QuestionnaireResponse::Group::Question::Answer, Range, Ratio, Reference, ReferralRequest, RelatedPerson, Resource, RiskAssessment, RiskAssessment::Prediction, SampledData, Schedule, SearchParameter, SearchParameter::Contact, Signature, Slot, Specimen, Specimen::Collection, Specimen::Container, Specimen::Treatment, StructureDefinition, StructureDefinition::Contact, StructureDefinition::Differential, StructureDefinition::Mapping, StructureDefinition::Snapshot, Subscription, Subscription::Channel, Substance, Substance::Ingredient, Substance::Instance, SupplyDelivery, SupplyRequest, SupplyRequest::When, TestScript, TestScript::Contact, TestScript::Fixture, TestScript::Metadata, TestScript::Metadata::Capability, TestScript::Metadata::Link, 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, ValueSet, ValueSet::CodeSystem, ValueSet::CodeSystem::Concept, ValueSet::CodeSystem::Concept::Designation, ValueSet::Compose, ValueSet::Compose::Include, ValueSet::Compose::Include::Concept, ValueSet::Compose::Include::Filter, ValueSet::Contact, ValueSet::Expansion, ValueSet::Expansion::Contains, ValueSet::Expansion::Parameter, VisionPrescription, VisionPrescription::Dispense

Instance Method Summary collapse

Methods included from Deprecate

deprecate

Constructor Details

#initialize(hash = {}) ⇒ Model

Returns a new instance of Model.



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

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_name, *_args, &_block) ⇒ Object

Raises:

  • (NoMethodError)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 39

def method_missing(method_name, *_args, &_block)
  if defined?(self.class::MULTIPLE_TYPES) && self.class::MULTIPLE_TYPES[method_name.to_s]
    self.class::MULTIPLE_TYPES[method_name.to_s].each do |type|
      type[0] = type[0].upcase
      value = send("#{method_name}#{type}".to_sym)
      return value unless value.nil?
    end
    return nil
  elsif !@extension.nil? && !@extension.empty?
    desired_extension = find_extension(@extension, method_name)
    unless desired_extension.first.nil?
      return desired_extension.first.value.nil? ? desired_extension.first : desired_extension.first.value
    end
  elsif !@modifierExtension.nil? && !@modifierExtension.empty?
    desired_extension = find_extension(@modifierExtension, method_name)
    unless desired_extension.first.nil?
      return desired_extension.first.value.nil? ? desired_extension.first : desired_extension.first.value
    end
  end
  raise NoMethodError.new("undefined method `#{method_name}' for #{self.class.name}", method_name)
end

Instance Method Details

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

allow two FHIR::DSTU2 models to be compared for equality



34
35
36
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 34

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

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



92
93
94
95
96
97
98
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 92

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



100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 100

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
  elsif left.is_a?(String) && right.is_a?(String)
    left.gsub(/[[:space:]]/, '') == right.gsub(/[[:space:]]/, '')
  else
    left == right
  end
end

#each_element(path = nil, &block) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 310

def each_element(path = nil, &block)
  self.class::METADATA.each do |element_name, |
    local_name = .fetch :local_name, element_name
    values = [instance_variable_get("@#{local_name}")].flatten.compact
    next if values.empty?

    values.each_with_index do |value, i|
      child_path =
        if path.nil?
          element_name
        else
          "#{path}.#{element_name}"
        end
      child_path += "[#{i}]" if ['max'] > 1
      yield value, , child_path
      value.each_element child_path, &block unless FHIR::DSTU2::PRIMITIVES.include? ['type']
    end
  end
  self
end

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

Returns:

  • (Boolean)


65
66
67
68
69
70
71
72
73
74
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 65

def equals?(other, exclude = [])
  self.class::METADATA.each do |key, value|
    next if exclude.include?(key)

    local_name = key
    local_name = value['local_name'] if value['local_name']
    return false unless compare_attribute(instance_variable_get("@#{local_name}".to_sym), other.instance_variable_get("@#{local_name}".to_sym), exclude)
  end
  true
end

#hashObject

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



22
23
24
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 22

def hash
  to_hash.hash
end

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



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 76

def mismatch(other, exclude = [])
  misses = []
  self.class::METADATA.each do |key, value|
    next if exclude.include?(key)

    local_name = key
    local_name = value['local_name'] if value['local_name']
    these = attribute_mismatch(instance_variable_get("@#{local_name}".to_sym), other.instance_variable_get("@#{local_name}".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)


288
289
290
291
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 288

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

#respond_to_missing?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 26

def respond_to_missing?(method_name, *)
  (defined?(self.class::MULTIPLE_TYPES) && self.class::MULTIPLE_TYPES[method_name.to_s]) ||
    (!@extension.nil? && !@extension.empty? && !find_extension(@extension, method_name).first.nil?) ||
    (!@modifierExtension.nil? && !@modifierExtension.empty? && !find_extension(@modifierExtension, method_name).first.nil?) ||
    super
end

#to_referenceObject



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

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

#valid?Boolean

Returns:

  • (Boolean)


114
115
116
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 114

def valid?
  validate.empty?
end

#validate(contained = nil) ⇒ Object



119
120
121
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 119

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

#validate_profile(metadata, contained = nil) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/fhir_dstu2_models/bootstrap/model.rb', line 123

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::DSTU2.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 StandardError
    {}
  end
  multiple_types.each do |prefix, suffixes|
    present = []
    suffixes.each do |suffix|
      typename = "#{prefix}#{suffix[0].upcase}#{suffix[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..]}"
      errors.delete(typename) unless present.include?(typename)
    end
  end
  errors.keep_if { |_k, v| (v && !v.empty?) }
end