Class: SheetsDB::Spreadsheet

Inherits:
Resource show all
Defined in:
lib/sheets_db/spreadsheet.rb

Defined Under Namespace

Classes: WorksheetAssociationAlreadyRegisteredError

Instance Attribute Summary

Attributes inherited from Resource

#google_drive_resource

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Resource

#==, #base_attributes, belongs_to_many, find_by_id, #initialize, register_association, set_resource_type

Constructor Details

This class inherits a constructor from SheetsDB::Resource

Class Method Details

.has_many(resource, worksheet_name:, class_name:) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/sheets_db/spreadsheet.rb', line 7

def self.has_many(resource, worksheet_name:, class_name:)
  register_worksheet_association(resource, worksheet_name: worksheet_name, class_name: class_name)
  define_method(resource) do
    @worksheets ||= {}
    @worksheets[resource] ||= Worksheet.new(
      spreadsheet: self,
      google_drive_resource: google_drive_resource.worksheet_by_title(worksheet_name),
      type: Support.constantize(class_name)
    )
  end
end

.register_worksheet_association(resource, worksheet_name:, class_name:) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/sheets_db/spreadsheet.rb', line 19

def self.register_worksheet_association(resource, worksheet_name:, class_name:)
  @associations ||= {}
  if @associations.fetch(resource, nil)
    raise WorksheetAssociationAlreadyRegisteredError
  end
  @associations[resource] = {
    worksheet_name: worksheet_name,
    class_name: class_name
  }
end

Instance Method Details

#find_association_by_id(association_name, id) ⇒ Object



30
31
32
# File 'lib/sheets_db/spreadsheet.rb', line 30

def find_association_by_id(association_name, id)
  find_associations_by_ids(association_name, [id]).first
end

#find_associations_by_attribute(association_name, attribute_name, value) ⇒ Object



38
39
40
# File 'lib/sheets_db/spreadsheet.rb', line 38

def find_associations_by_attribute(association_name, attribute_name, value)
  send(association_name).find_by_attribute(attribute_name, value)
end

#find_associations_by_ids(association_name, ids) ⇒ Object



34
35
36
# File 'lib/sheets_db/spreadsheet.rb', line 34

def find_associations_by_ids(association_name, ids)
  send(association_name).find_by_ids(ids)
end

#select_from_association(association_name, &block) ⇒ Object



42
43
44
# File 'lib/sheets_db/spreadsheet.rb', line 42

def select_from_association(association_name, &block)
  send(association_name).select(&block)
end