Module: RescueGroups::Relationable::ClassMethods
- Defined in:
- lib/relationable.rb
Instance Method Summary collapse
-
#belongs_to(relationship) ⇒ Object
method: belongs_to purpose: define methods that denote a relationship between the class including this module and another.
-
#has_many(relationship) ⇒ Object
method: has_many purpose: define methods that denote a relationship between the class including this module and another.
Instance Method Details
#belongs_to(relationship) ⇒ Object
method: belongs_to purpose: define methods that denote a relationship
between the class including this module
and another.
When included, it defines methods: relationship_id
relationship_id=
relationship
relationship=
example:
class Foo
include Relationable
belongs_to :bar
end
param: relationship - <Symbol> - name of the class that a relationship
is intended for
return: nil
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/relationable.rb', line 28 def belongs_to(relationship) define_method relationship do model = instance_variable_get(:"@#{ relationship }") return model unless model.nil? if id_to_fetch = self.send(:"#{ relationship }_id") klass = RescueGroups.constantize(relationship) self.send(:"#{ relationship }=", klass.find(id_to_fetch)) end end attr_writer relationship attr_accessor :"#{ relationship }_id" end |
#has_many(relationship) ⇒ Object
method: has_many purpose: define methods that denote a relationship
between the class including this module
and another.
When included, it defines methods: relationship
relationship=
example:
class Foo
include Relationable
has_many :bars
end
param: relationship - <Symbol> - name of the class that a relationship
is intended for
return: nil
59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/relationable.rb', line 59 def has_many(relationship) define_method relationship do temp = instance_variable_get(:"@#{ relationship }") return temp unless temp.nil? || temp.empty? klass = RescueGroups.constantize(relationship) foreign_key = "#{ self.class.to_s.split('::').last.downcase }_id" klass.where(foreign_key.to_sym => @id) end attr_writer relationship end |