Class: ActiveRecord::Base

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

Direct Known Subclasses

Association2, Associator::Association

Class Method Summary collapse

Class Method Details

.associated(opts = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/associator.rb', line 10

def self.associated	opts={}
	@from_type = name.downcase
	if opts[:with]
		@to_type = opts[:with].to_s.downcase
		@class_name = opts[:class_name] || false
		@table_name = @to_type.pluralize if @to_type
		@table_name = @class_name.pluralize if @class_name
		@table_name = opts[:table] if opts[:table]

		# http://stackoverflow.com/questions/8545360/finder-sql-does-not-parse-string-with-rails
		if @class_name
		  eval "
 	      has_many '#{@to_type}', :class_name => '#{@class_name}', :finder_sql => ->(record) do
 	        finder record, '#{@table_name}', '#{@from_type}', '#{@to_type}'
 	      end
 	    "
		else
		  eval "
 	      has_many '#{@to_type}', :finder_sql => ->(record) do
 	        finder record, '#{@table_name}', '#{@from_type}', '#{@to_type}'
 	      end
 	    "
		end
		eval "
 			define_method(:add_associated) do |obj|
 			  Associator::Association.create(:from => id, :from_type => '#{@from_type}', :to => obj.id, :to_type => '#{@to_type}')
 			end

 			define_method(:del_associated) do |obj|
 			  association = Associator::Association.where(:from => id, :from_type => '#{@from_type}', :to => obj.id, :to_type => '#{@to_type}')
 			  Associator::Association.destroy(association) if association && association.size == 1
 			end
		"
   end
end