questions about Class#remove_class implementation

Discussion in 'Ruby' started by Xavier Noria, Nov 11, 2006.

  1. Xavier Noria

    Xavier Noria Guest

    I am reading Rails's Class#remove_class:

    def remove_class(*klasses)
    klasses.flatten.each do |klass|
    # Skip this class if there is nothing bound to this name
    next unless defined?(klass.name)

    basename = klass.to_s.split("::").last
    parent = klass.parent

    # Skip this class if it does not match the current one bound
    to this name
    next unless parent.const_defined?(basename) && klass =
    parent.const_get(basename)

    parent.send :remove_const, basename unless parent == klass
    end
    end

    and have a few questions:

    1. Do you think there's a reason for using Module#name
    first and Module#to_s afterwards? Looks to me that
    they are only different for singleton classes, and
    for those ones split does not provide a meaningful
    chunk anyway:

    irb(main):002:0> klass = (class << ActiveRecord::Base; self; end)
    => #<Class:ActiveRecord::Base>
    irb(main):003:0> klass.name
    => ""
    irb(main):004:0> klass.to_s.split("::").last
    => "Base>"

    2. In which situation do you think parent.const_defined?(basename)
    && klass = parent.const_get(basename) could return false?

    3. Does parent.send :remove_const effectively unload the
    class definition from the interpreter? If yes, what
    would happen to some dangling instance afterwards if
    some method of that class was invoked? Would the object
    still hold some kind of relationship to the now non-
    existent class that could result in some fatal error?

    4. When could parent == klass hold at the end of the block?

    -- fxn

    PS: Rails defines Module#parent as

    def parent
    parent_name = name.split('::')[0..-2] * '::'
    parent_name.empty? ? Object : parent_name.constantize
    end
     
    Xavier Noria, Nov 11, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Rowell
    Replies:
    0
    Views:
    564
    John Rowell
    Apr 22, 2004
  2. E11
    Replies:
    1
    Views:
    4,844
    Thomas Weidenfeller
    Oct 12, 2005
  3. Michael Tsang
    Replies:
    32
    Views:
    1,139
    Richard Bos
    Mar 1, 2010
  4. Michael Tsang
    Replies:
    54
    Views:
    1,219
    Phil Carmody
    Mar 30, 2010
  5. sanket
    Replies:
    7
    Views:
    1,046
    Tsung
    Nov 3, 2011
Loading...

Share This Page