# Defines the relations between ActiveRepository objects. # # Author:: Caio Torres (mailto:efreesen@gmail.com) # License:: GPL module ActiveRepository module Associations def self.included(base) base.extend Methods end module Methods # Defines "has many" type relation between ActiveRepository objects def has_many(association_id, options = {}) define_method(association_id) do options = { class_name: association_id.to_s.classify, foreign_key: self.class.to_s.foreign_key }.merge(options) klass = options[:class_name].constantize objects = [] klass.where(options[:foreign_key] => id) end end # Defines "has one" type relation between ActiveRepository objects def has_one(association_id, options = {}) define_method(association_id) do options = { class_name: association_id.to_s.classify, foreign_key: self.class.to_s.foreign_key }.merge(options) scope = options[:class_name].constantize scope = scope.where(options[:conditions]) if options[:conditions] send_params = scope.respond_to?(:find_by) ? ["find_by", id: id] : ["find_by_id", id] scope.send(*send_params) end end # Defines "belongs to" type relation between ActiveRepository objects def belongs_to(association_id, options = {}) options = { class_name: association_id.to_s.classify, foreign_key: association_id.to_s.foreign_key }.merge(options) field options[:foreign_key].to_sym define_method(association_id) do klass = options[:class_name].constantize id = send(options[:foreign_key]) if id.present? object = klass.respond_to?(:find_by) ? klass.find_by(id: id) : klass.find_by_id(id) else nil end end define_method("#{association_id}=") do |new_value| attributes.delete(association_id.to_sym) send("#{options[:foreign_key]}=", (new_value.try(:id) ? new_value.id : new_value)) end end end end end