Module: Hearsay::Referencer::ClassMethods
- Defined in:
- lib/hearsay/referencer.rb
Instance Method Summary collapse
-
#references(source_name, options = {}) ⇒ Object
Public: Set up referenceable assocations.
Instance Method Details
#references(source_name, options = {}) ⇒ Object
Public: Set up referenceable assocations
source_name - The name of the source association (model being referenced) options - Options hash (default: {}):
:attribute - Name of model attribute containing text references (required)
:matcher - Regular expression to match on (default: /#([0-9]+)/i)
:finder - The method used to find referenced objects (default: :find_by_id)
:class_name - The class of the source association, if the name can't be inferred from
the association name (optional)
:collection - A class or a proc that referenceable objects are scoped to (optional)
Examples
references :issues, :attribute => :summary, :matcher => /#([0-9]+)/i, :finder => :find_by_number
references :referenced_users,
:attribute => :body,
:class_name => 'User',
:matcher => /@(\w)/i,
:finder => :find_by_username
Returns nothing.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/hearsay/referencer.rb', line 30 def references(source_name, = {}) send(:include, Hearsay::Referencer::InstanceMethods) unless self.included_modules.include?(Hearsay::Referencer::InstanceMethods) attribute_name = .delete(:attribute) raise ArgumentError, ":attribute option is required for references" if attribute_name.blank? association_name = "#{source_name.to_s.singularize}_references".to_sym class_eval do has_many(association_name, :as => :referencer, :class_name => 'Reference', :conditions => {:attribute_name => attribute_name}, :dependent => :destroy) unless self.respond_to?(association_name) has_many source_name, :through => association_name, :source => :referenceable, :source_type => ([:class_name] || source_name.to_s.classify) before_save proc { self.send(:create_references, source_name, attribute_name, ) } end end |