Module: Sack::Database::Model::Relationships::ClassMethods

Defined in:
lib/sack/database/model/relationships.rb,
lib/sack/database/model/relationships/has_many.rb,
lib/sack/database/model/relationships/belongs_to.rb

Overview

Class Methods

Instance Method Summary collapse

Instance Method Details

#belongs_to(options) ⇒ Object

Belongs To: Defines the ‘slave’ end of any relationship (the one that holds the other entity’s ID).

Parameters:

  • options (Object)

    Either a Symbol indicating both the name of the relationship and the target model, or an option Hash defining the relationship - see README



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/sack/database/model/relationships/belongs_to.rb', line 22

def belongs_to options

	# Check Options
	if options.is_a? Hash

		# Internalise Options (so we can mess it up)
		options = options.clone

		# Pull Relationship Name & Target Model
		name, target_model_name = options.first
		options.delete name
	else

		# Acquire everything from just a Symbol
		name = options
		target_model_name = name
	end

	# Construct Proxy Method Module
	proxy = Module.new do

		# Proxy Method for Relationship:
		# Allows fetching entities for a given belongs-to relationship.
		define_method name do |db, data|

			# Find Target Model
			target_model = @model_root.const_get target_model_name.to_s.camelcase

			# Fetch Relationship Entity
			target_model.find db, data[name]
		end
	end

	# Extend Model with Proxy
	@model.extend proxy
end

#has_many(options) ⇒ Object

Has Many: Defines the ‘one’ side a one-to-many relationship.

Parameters:

  • options (Hash)

    Options defining the relationship - see README



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sack/database/model/relationships/has_many.rb', line 22

def has_many options

	# Internalise Options (so we can mess it up)
	options = options.dclone

	# Pull Relationship Name & Target Model
	name, target_model_name = options.first
	options.delete name

	# Determine Foreign Key (which field in the remote model holds our ID)
	foreign_key = options[:fk] || table_name

	# Register Relationship
	relationships[name] = { target: target_model_name, fk: foreign_key, options: options.dclone }

	# Construct Proxy Method Module
	proxy = Module.new do

		# Proxy Method for Relationship:
		# Allows fetching entities for a given has-many relationship.
		define_method name do |db, data|

			# Find Target Model
			target_model = @model_root.const_get target_model_name.to_s.camelcase

			# Fetch Relationship Entities
			target_model.fetch_by db, foreign_key, data[:id]
		end
	end

	# Extend Model with Proxy
	@model.extend proxy
end

#relationshipsObject

Relationships: Gets the relationships for the Model.



34
35
36
# File 'lib/sack/database/model/relationships.rb', line 34

def relationships
	@relationships ||= {}
end