Class inherits from

Posted on August 3rd, 2008 @ 04:41 PM by mark

I wanted to know if a class was an Active Record class. I couldn’t find an easy way to do it in Ruby so I monkey patches the Class object like so (assuming Person is an active record model object).

1
2
3
4
5
6
7
8
9
10
11

class Class
  def inherits_from?(klass, me=self)
    return false if me.nil?
    return true if me == klass
    inherits_from? klass, me.superclass
  end
end

>> Person.inherits_from? ActiveRecord::Base
=> true

, , ,

Comments

  • Marcus Crafter on 03 Aug 23:42

    Hi Mark,

    I think you can do this using ancestors as well mate:

    $> irb

    class A; end => nil class B < A; end => nil B.ancestors => [B, A, Object, Kernel] A.ancestors => [A, Object, Kernel]

    Hope this helps.

    Cheers,

    Marcus

  • Mark Mansour on 05 Aug 13:23

    Great tip Marcus - I’m going to convert this code (or maybe just remove it)

Comments are closed