Class: ActiveFedora::ModelClassifier

Inherits:
Object
  • Object
show all
Defined in:
lib/active_fedora/model_classifier.rb

Overview

Translate model names to classes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(class_names, default: ActiveFedora::Base) ⇒ ModelClassifier

Returns a new instance of ModelClassifier.



30
31
32
33
# File 'lib/active_fedora/model_classifier.rb', line 30

def initialize(class_names, default: ActiveFedora::Base)
  @class_names = Array(class_names)
  @default = default
end

Instance Attribute Details

#class_namesObject (readonly)

Returns the value of attribute class_names.



28
29
30
# File 'lib/active_fedora/model_classifier.rb', line 28

def class_names
  @class_names
end

#defaultObject (readonly)

Returns the value of attribute default.



28
29
30
# File 'lib/active_fedora/model_classifier.rb', line 28

def default
  @default
end

Class Method Details

.class_from_string(full_class_name, container_class = Kernel) ⇒ Object

Convenience method for getting class constant based on a string

Examples:

ActiveFedora::Model.class_from_string("Om")
=> Om
ActiveFedora::Model.class_from_string("ActiveFedora::RdfNode::TermProxy")
=> ActiveFedora::RdfNode::TermProxy

Search within ActiveFedora::RdfNode for a class called “TermProxy”

ActiveFedora::Model.class_from_string("TermProxy", ActiveFedora::RdfNode)
=> ActiveFedora::RdfNode::TermProxy


13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/active_fedora/model_classifier.rb', line 13

def self.class_from_string(full_class_name, container_class = Kernel)
  container_class = container_class.name if container_class.is_a? Module
  container_parts = container_class.split('::')
  (container_parts + full_class_name.split('::')).flatten.inject(Kernel) do |mod, class_name|
    if mod == Kernel
      Object.const_get(class_name)
    elsif mod.const_defined? class_name.to_sym
      mod.const_get(class_name)
    else
      container_parts.pop
      class_from_string(class_name, container_parts.join('::'))
    end
  end
end

Instance Method Details

#best_model(opts = {}) ⇒ Object

Select the “best” class from the list of class names. We define

the "best" class as:
 - a subclass of the given default, base class
 - preferring subclasses over the parent class


48
49
50
51
52
53
54
55
56
57
# File 'lib/active_fedora/model_classifier.rb', line 48

def best_model(opts = {})
  best_model_match = opts.fetch(:default, default)

  models.each do |model_value|
    # If there is an inheritance structure, use the most specific case.
    best_model_match = model_value if best_model_match.nil? || best_model_match > model_value
  end

  best_model_match
end

#modelsObject

Convert all the provided class names to class instances



37
38
39
40
41
# File 'lib/active_fedora/model_classifier.rb', line 37

def models
  class_names.map do |uri|
    classify(uri)
  end.compact
end