Module: Dor::Identifiable

Extended by:
ActiveSupport::Concern
Includes:
Eventable, Upgradable, SolrDocHelper
Included in:
Abstract, AdminPolicyObject, BasicItem, Collection, Publishable, Set, WorkflowObject
Defined in:
lib/dor/models/identifiable.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

@@collection_hash =
{}
@@apo_hash =
{}
@@hydrus_apo_hash =
{}
@@hydrus_collection_hash =
{}

Instance Method Summary collapse

Methods included from Upgradable

add_upgrade_callback, included, run_upgrade_callbacks, #upgrade!

Methods included from Eventable

#add_event

Methods included from SolrDocHelper

#add_solr_value

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object

Syntactic sugar for identifying applied DOR Concerns e.g., obj.is_identifiable? is the same as obj.is_a?(Dor::Identifiable)



85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/dor/models/identifiable.rb', line 85

def method_missing sym, *args
  if sym.to_s =~ /^is_(.+)\?$/
    begin
      klass = Dor.const_get $1.capitalize.to_sym
      return self.is_a?(klass)
    rescue NameError
      return false
    end
  else
    super
  end
end

Instance Method Details

#add_other_Id(type, val) ⇒ Object



180
181
182
183
184
185
186
# File 'lib/dor/models/identifiable.rb', line 180

def add_other_Id(type,val)
  if self..otherId(type).length>0
    raise 'There is an existing entry for '+node_name+', consider using update_other_identifier.'
  end
   = self.
  .add_otherId(type+':'+val)
end

#add_tag(tag, type = :tag, attrs = {}) ⇒ String, Nokogiri::XML::Element

Add a tag for an item If you are adding just a :tag att

release tag example:

item.add_tag(true,:release,{:tag=>'Fitch : Batch2',:what=>'self',:to=>'Searchworks',:who=>'petucket'})

Returns:

  • (String)

    returned if this function is called with invalid parameters, eg a lack of :who for release_tag

  • (Nokogiri::XML::Element)

    the tag added if successful

Raises:

  • (RuntimeError)

    Raised if the tag already exists on the item or the tag is not of the form a:b



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/dor/models/identifiable.rb', line 282

def add_tag(tag, type=:tag, attrs={})
  needs_timestamp = [:release] #If you want a tag to get a timestamp attribute, add its symbol here
   = self.
  normalized_tag = validate_and_normalize_tag(tag, .tags) if type != :release #Release tags are always boolean, so skip this step
  normalized_tag = tag.to_s if type == :release #just keep the boolean if we have just have a release
    
  attrs[:when] = Time.now.utc.iso8601 if needs_timestamp.include? type
  

  if type == :release 
    valid_release_attributes_and_tag(tag, attrs)
    attrs[:tag] = normalize_tag_arr(validate_tag_format(attrs[:tag])) if attrs[:tag] != nil #:tag must be a valid administrative tag
  end
  
  return .add_value(type, normalized_tag) if attrs == {}
  return .add_value(type, normalized_tag, attrs) if attrs != {}
end

#content_type_tagObject

helper method to get just the content type tag



78
79
80
81
# File 'lib/dor/models/identifiable.rb', line 78

def content_type_tag
  =tags.select {|tag| tag.include?('Process : Content Type')}
  .size == 1 ? [0].split(':').last.strip : ""
end

#initialize(attrs = {}) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/dor/models/identifiable.rb', line 21

def initialize attrs={}
  if Dor::Config.suri.mint_ids
    unless attrs[:pid]
      attrs = attrs.merge!({:pid=>Dor::SuriService.mint_id, :new_object => true})
    end
  end
  super
end

#normalize_tag(tag_str) ⇒ Object

take a tag string and return a normalized tag string



228
229
230
# File 'lib/dor/models/identifiable.rb', line 228

def normalize_tag(tag_str)
  return normalize_tag_arr(split_tag_to_arr(tag_str))
end

#normalize_tag_arr(tag_arr) ⇒ Object

turn a tag array back into a tag string with a standard format



223
224
225
# File 'lib/dor/models/identifiable.rb', line 223

def normalize_tag_arr(tag_arr)
  return tag_arr.join(' : ')
end

#release_tag_node_to_hash(rtag) ⇒ Object

method to convert one release element into an array

return [Hash] in the form of => String :attrs = Hash

Parameters:

  • rtag (Nokogiri::XML::Element)

    the release tag element



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/dor/models/identifiable.rb', line 57

def release_tag_node_to_hash(rtag)
  to = 'to'
  release = 'release'
  when_word = 'when' #TODO: Make to and when_word load from some config file instead of hardcoded here
  attrs = rtag.attributes
  return_hash = { :to => attrs[to].value }
  attrs.tap { |a| a.delete(to)}
  attrs[release] = rtag.text.downcase == "true" #save release as a boolean
  return_hash[:attrs] = attrs
  
  #convert all the attrs beside :to to strings, they are currently Nokogiri::XML::Attr
  (return_hash[:attrs].keys-[to]).each do |a|
    return_hash[:attrs][a] =  return_hash[:attrs][a].to_s if a != release
  end
  
  return_hash[:attrs][when_word] = Time.parse(return_hash[:attrs][when_word]) #convert when to a datetime
  
  return return_hash
end

#release_tagsNokogiri::XML::NodeSet

helper method to get the release tags as a nodeset

Returns:

  • (Nokogiri::XML::NodeSet)

    of all release tags and their attributes



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dor/models/identifiable.rb', line 38

def release_tags
  release_tags = self..ng_xml.xpath('//release')
  return_hash = {}
  release_tags.each do |release_tag|
    hashed_node = self.release_tag_node_to_hash(release_tag)
    if return_hash[hashed_node[:to]] != nil
      return_hash[hashed_node[:to]] << hashed_node[:attrs]
    else
       return_hash[hashed_node[:to]] = [hashed_node[:attrs]]
    end
  end
  return return_hash
end

#remove_other_Id(type, val = nil) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/dor/models/identifiable.rb', line 202

def remove_other_Id(type,val=nil)
  ds_xml=self..ng_xml
  #split the thing they sent in to find the node name
  removed=false

  ds_xml.search('//otherId[@name=\''+type+'\']').each do |node|
    if node.content===val or val==nil
      node.remove
      removed=true
    end
  end
  return removed
end

#remove_tag(tag) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/dor/models/identifiable.rb', line 326

def remove_tag(tag)
   = self.
  ds_xml = .ng_xml
  removed = false
  ds_xml.search('//tag').each do |node|
    if normalize_tag(node.content) === normalize_tag(tag)
      node.remove
      removed = true
    end
  end
  return removed
end

#set_source_id(source_id) ⇒ Object



176
177
178
# File 'lib/dor/models/identifiable.rb', line 176

def set_source_id(source_id)
  self..sourceId = source_id
end

#split_tag_to_arr(tag_str) ⇒ Object

turns a tag string into an array with one element per tag part. split on “:”, disregard leading and trailing whitespace on tokens.



218
219
220
# File 'lib/dor/models/identifiable.rb', line 218

def split_tag_to_arr(tag_str)
  return tag_str.split(":").map {|str| str.strip}
end

#tagsObject

helper method to get the tags as an array



31
32
33
# File 'lib/dor/models/identifiable.rb', line 31

def tags
  self..tag
end

#to_solr(solr_doc = Hash.new, *args) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/dor/models/identifiable.rb', line 102

def to_solr(solr_doc=Hash.new, *args)
  self.assert_content_model
  super(solr_doc)
  solr_doc[Dor::INDEX_VERSION_FIELD] = Dor::VERSION
  solr_doc[solr_name('indexed_at',:date)] = Time.now.utc.xmlschema
  add_solr_value(solr_doc, 'indexed_day', Time.now.beginning_of_day.utc.xmlschema, :string, [:searchable, :facetable])
  datastreams.values.each do |ds|
    unless ds.new?
      add_solr_value(solr_doc,'ds_specs',ds.datastream_spec_string,:string,[:displayable])
    end
  end
  add_solr_value(solr_doc, 'title_sort', self.label, :string, [:sortable])
  rels_doc = Nokogiri::XML(self.datastreams['RELS-EXT'].content)
  apos=rels_doc.search('//rdf:RDF/rdf:Description/hydra:isGovernedBy','hydra' => 'http://projecthydra.org/ns/relations#', 'fedora' => 'info:fedora/fedora-system:def/relations-external#', 'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'   )
  apos.each do |apo_node|
    druid=apo_node['rdf:resource']
    if druid
      druid=druid.gsub('info:fedora/','')
      if @@apo_hash.has_key? druid or @@hydrus_apo_hash.has_key? druid
        add_solr_value(solr_doc, "hydrus_apo_title", @@hydrus_apo_hash[druid], :string, [:searchable, :facetable]) if @@hydrus_apo_hash.has_key? druid
        add_solr_value(solr_doc, "apo_title", @@apo_hash[druid] , :string, [:searchable, :facetable]) if @@apo_hash.has_key? druid
      else
        begin
          apo_object=Dor.find(druid)
          if apo_object.tags.include? 'Project : Hydrus'
            add_solr_value(solr_doc, "hydrus_apo_title", apo_object.label, :string, [:searchable, :facetable])
            @@hydrus_apo_hash[druid]=apo_object.label
          else
            add_solr_value(solr_doc, "apo_title", apo_object.label, :string, [:searchable, :facetable])
            @@apo_hash[druid]=apo_object.label
          end
        rescue
          add_solr_value(solr_doc, "apo_title", druid, :string, [:searchable, :facetable])
        end
      end
    end
  end
  collections=rels_doc.search('//rdf:RDF/rdf:Description/fedora:isMemberOfCollection','fedora' => 'info:fedora/fedora-system:def/relations-external#', 'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'   )
  collections.each do |collection_node|
    druid=collection_node['rdf:resource']
    if(druid)
      druid=druid.gsub('info:fedora/','')
      if @@collection_hash.has_key? druid or @@hydrus_collection_hash.has_key? druid
        add_solr_value(solr_doc, "hydrus_collection_title", @@hydrus_collection_hash[druid], :string, [:searchable, :facetable]) if @@hydrus_collection_hash.has_key? druid
        add_solr_value(solr_doc, "collection_title", @@collection_hash[druid], :string, [:searchable, :facetable]) if @@collection_hash.has_key? druid
      else
        begin
          collection_object=Dor.find(druid)
          if collection_object.tags.include? 'Project : Hydrus'
            add_solr_value(solr_doc, "hydrus_collection_title", collection_object.label, :string, [:searchable, :facetable])
            @@hydrus_collection_hash[druid]=collection_object.label
          else
            add_solr_value(solr_doc, "collection_title", collection_object.label, :string, [:searchable, :facetable])
            @@collection_hash[druid]=collection_object.label
          end
        rescue
          add_solr_value(solr_doc, "collection_title", druid, :string, [:searchable, :facetable])
        end
      end
    end
  end
  # Fix for ActiveFedora 3.3 to ensure all date fields are properly formatted as UTC XML Schema datetime strings
  solr_doc.each_pair { |k,v|
    if k =~ /_dt|_date$/
      if v.is_a?(Array)
        solr_doc[k] = v.collect { |t| Time.parse(t.to_s).utc.xmlschema }
      else
        solr_doc[k] = Time.parse(v.to_s).utc.xmlschema
      end
    end
  }

  solr_doc
end

#update_other_Id(type, new_val, val = nil) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/dor/models/identifiable.rb', line 188

def update_other_Id(type,new_val, val=nil)
   = self.
  ds_xml=.ng_xml
  #split the thing they sent in to find the node name
  updated=false
  ds_xml.search('//otherId[@name=\''+type+'\']').each do |node|
    if node.content==val or val==nil
      node.content=new_val
      updated=true
    end
  end
  return updated
end

#update_tag(old_tag, new_tag) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/dor/models/identifiable.rb', line 339

def update_tag(old_tag, new_tag)
   = self.
  ds_xml = .ng_xml
  updated = false
  ds_xml.search('//tag').each do |node|
    if normalize_tag(node.content) == normalize_tag(old_tag)
      node.content = normalize_tag(new_tag)
      updated = true
    end
  end
  return updated
end

#valid_release_attributes_and_tag(tag, attrs = {}) ⇒ Boolean

Determine if the supplied tag is a valid release tag that meets all requirements

Returns:

  • (Boolean)

    Returns true if no errors found



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/dor/models/identifiable.rb', line 308

def valid_release_attributes_and_tag(tag, attrs={})
  raise ":when is not iso8601" if attrs[:when].match('\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z') == nil
  [:who, :to, :what].each do |check_attr|
    raise "#{check_attr} not supplied as a String" if attrs[check_attr].class != String
  end
  
  what_correct = false
  ['self', 'collection'].each do |allowed_what_value|
    what_correct = true if attrs[:what] == allowed_what_value
  end
  raise ":what must be self or collection" if not what_correct
  
  raise "the value set for this tag is not a boolean" if !!tag != tag
   = self.
  validate_tag_format(attrs[:tag]) if attrs[:tag] != nil #Will Raise exception if invalid tag
  return true
end

#validate_and_normalize_tag(tag_str, existing_tag_list) ⇒ Object

take a proposed tag string and a list of the existing tags for the object being edited. if the proposed tag is valid, return it in normalized form. if not, raise an exception with an explanatory message.



235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/dor/models/identifiable.rb', line 235

def validate_and_normalize_tag(tag_str, existing_tag_list)
  tag_arr = validate_tag_format(tag_str)

  # note that the comparison for duplicate tags is case-insensitive, but we don't change case as part of the normalized version 
  # we return, because we want to preserve the user's intended case.
  normalized_tag = normalize_tag_arr(tag_arr)
  dupe_existing_tag = existing_tag_list.detect { |existing_tag| normalize_tag(existing_tag).downcase == normalized_tag.downcase }
  if dupe_existing_tag
    raise "An existing tag (#{dupe_existing_tag}) is the same, consider using update_tag?"
  end

  return normalized_tag
end

#validate_tag_format(tag_str) ⇒ Array

Ensure that an administrative tag meets the proper mininum format

Returns:

  • (Array)

    the tag split into an array via ‘:’



254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/dor/models/identifiable.rb', line 254

def validate_tag_format(tag_str)
  tag_arr = split_tag_to_arr(tag_str)

  if tag_arr.length < 2
    raise "Invalid tag structure:  tag '#{tag_str}' must have at least 2 elements"
  end

  if tag_arr.detect {|str| str.empty?}
    raise "Invalid tag structure:  tag '#{tag_str}' contains empty elements"
  end
  
  return tag_arr
  
end