PageRenderTime 25ms CodeModel.GetById 14ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/has_parent.rb

http://acts-crummy.googlecode.com/
Ruby | 35 lines | 19 code | 5 blank | 11 comment | 2 complexity | 560a8d7c80235c5510fbde730b0e512a MD5 | raw file
 1module ActsCrummy #:nodoc:
 2  # This module is mixed into ActiveRecord::Base to provide methods to help define
 3  # the direct hierarcy in the model structure of a project, so that breadcrumbs
 4  # can be rendered dynamically from it.
 5
 6  module HasParent
 7
 8    # the self.included/class << base trick is all for the sake
 9    # seemingly neceesary class variable @@parent_label
10    def self.included(base) #:nodoc:
11
12      # only apply this to inheriting classes, not to the parent itself
13      # (probably ActiveRecord::Base)
14      def base.inherited(subclass)
15        super if defined? super
16
17        class << subclass
18          def is_child_to lbl #:doc:
19            if method_defined? :parent
20              raise ArgumentError, 'Only one parent can be defined for a given model.'
21            end
22
23            # this way we don't add the parent method unless
24            # it's actually going to be used.  if we just added
25            # to the class outright it may mess with the model
26            # definition.
27            send(:define_method, :parent) do
28              send(lbl)
29            end
30          end
31        end
32      end
33    end
34  end
35end