Class: JCF::CF::Relationships

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/jcf/cf/relationships.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(belongs_to, relationships = {}) ⇒ Relationships

Returns a new instance of Relationships.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
# File 'lib/jcf/cf/relationships.rb', line 12

def initialize(belongs_to, relationships = {})
  relationships = {} if relationships.nil?
  raise ArgumentError, "expects a hash" unless relationships.is_a?(Hash)

  @belongs_to = belongs_to
  @relationships = convert_to_classes(relationships)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/jcf/cf/relationships.rb', line 44

def method_missing(method_name, *args, &block)
  if relationship?(method_name)
    klass = get_klass(method_name)

    matches = @relationships.filter_map do |relationship|
      relationship.instance_of?(klass) ? relationship : nil
    end

    matches.size == 1 ? matches.first : matches
  else
    super
  end
end

Instance Attribute Details

#belongs_toObject (readonly)

Returns the value of attribute belongs_to.



10
11
12
# File 'lib/jcf/cf/relationships.rb', line 10

def belongs_to
  @belongs_to
end

Instance Method Details

#each(&block) ⇒ Object



20
21
22
# File 'lib/jcf/cf/relationships.rb', line 20

def each(&block)
  @relationships&.each(&block)
end

#inspectObject



24
25
26
# File 'lib/jcf/cf/relationships.rb', line 24

def inspect
  @relationships.inspect
end

#relationship?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
37
38
# File 'lib/jcf/cf/relationships.rb', line 28

def relationship?(method_name)
  klass = get_klass(method_name)

  matches = @relationships.filter_map do |relationship|
    relationship.instance_of?(klass) ? relationship : nil
  end.compact

  matches.any?
rescue NameError
  false
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/jcf/cf/relationships.rb', line 40

def respond_to_missing?(method_name, include_private = false)
  relationship?(method_name) || super
end

#to_sObject



58
59
60
61
62
# File 'lib/jcf/cf/relationships.rb', line 58

def to_s
  @relationships.collect do |relationship|
    "#{relationship.class.name.demodulize}: #{relationship.name || ""} (#{relationship.guid})"
  end.join(", ")
end