Class: Regolith::RegolithAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/regolith/regolith_association.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent_record, association_name, service, type, foreign_key_value = nil) ⇒ RegolithAssociation

Returns a new instance of RegolithAssociation.



4
5
6
7
8
9
10
11
# File 'lib/regolith/regolith_association.rb', line 4

def initialize(parent_record, association_name, service, type, foreign_key_value = nil)
  @parent_record = parent_record
  @association_name = association_name
  @service = service
  @type = type
  @foreign_key_value = foreign_key_value
  @loaded_records = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



41
42
43
# File 'lib/regolith/regolith_association.rb', line 41

def method_missing(method_name, *args, &block)
  all.send(method_name, *args, &block)
end

Instance Method Details

#allObject



36
37
38
39
# File 'lib/regolith/regolith_association.rb', line 36

def all
  load_records unless @loaded_records
  @loaded_records
end

#create!(attributes = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/regolith/regolith_association.rb', line 13

def create!(attributes = {})
  case @type
  when :has_many
    # For has_many, set the foreign key to parent's id
    foreign_key = "#{@parent_record.class.name.underscore}_id"
    attributes[foreign_key] = @parent_record.id
    
    # Create in the target service
    target_class = @association_name.to_s.singularize.camelize.constantize
    target_class.create(attributes)
  end
end

#firstObject



26
27
28
29
30
31
32
33
34
# File 'lib/regolith/regolith_association.rb', line 26

def first
  case @type
  when :belongs_to
    target_class = @association_name.to_s.camelize.constantize
    target_class.find(@foreign_key_value)
  when :has_many
    all.first
  end
end

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

Returns:

  • (Boolean)


45
46
47
# File 'lib/regolith/regolith_association.rb', line 45

def respond_to_missing?(method_name, include_private = false)
  all.respond_to?(method_name, include_private) || super
end