/lib/has_parent.rb

http://acts-crummy.googlecode.com/ · Ruby · 35 lines · 19 code · 5 blank · 11 comment · 2 complexity · 560a8d7c80235c5510fbde730b0e512a MD5 · raw file

  1. module 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. module HasParent
  6. # the self.included/class << base trick is all for the sake
  7. # seemingly neceesary class variable @@parent_label
  8. def self.included(base) #:nodoc:
  9. # only apply this to inheriting classes, not to the parent itself
  10. # (probably ActiveRecord::Base)
  11. def base.inherited(subclass)
  12. super if defined? super
  13. class << subclass
  14. def is_child_to lbl #:doc:
  15. if method_defined? :parent
  16. raise ArgumentError, 'Only one parent can be defined for a given model.'
  17. end
  18. # this way we don't add the parent method unless
  19. # it's actually going to be used. if we just added
  20. # to the class outright it may mess with the model
  21. # definition.
  22. send(:define_method, :parent) do
  23. send(lbl)
  24. end
  25. end
  26. end
  27. end
  28. end
  29. end
  30. end