Module: Plant::Reflection

Defined in:
lib/reflection.rb

Constant Summary collapse

@@reflections =
{}

Class Method Summary collapse

Class Method Details

.clone(object, id) ⇒ Object



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

def self.clone object, id
  clone = object.class.new
  cloner = Proc.new {|attribute| clone.send(attribute.to_s + "=", object.send(attribute))}
  reflection = @@reflections[object.class]
  
  clone.id = id
  reflection[:attributes].keys.each(&cloner)
  [:has_many, :has_one, :belongs_to].each {|relation| reflection[relation].each(&cloner)}

  clone
end

.foreign_key(object, association) ⇒ Object



35
36
37
# File 'lib/reflection.rb', line 35

def self.foreign_key object, association
  object.class.name.underscore + '_id'
end

.has_many_association?(klass, method) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/reflection.rb', line 26

def self.has_many_association? klass, method
  @@reflections[klass][:has_many].include?(method)
end

.has_one_association?(klass, method) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/reflection.rb', line 30

def self.has_one_association? klass, method
  @@reflections[klass][:has_one].include?(method)
  
end

.reflect(klass) ⇒ Object



5
6
7
8
9
10
11
12
# File 'lib/reflection.rb', line 5

def self.reflect klass
  return if @@reflections[klass]
  associations = lambda {|klass, macro| klass.reflect_on_all_associations(macro).map{|association| association.name} || []}

  reflection = @@reflections[klass] = Hash.new
  [:has_many, :has_one, :belongs_to].each {|relation| reflection[relation] = associations.call(klass, relation)}
  reflection[:attributes] = klass.new.attributes
end