views:

137

answers:

1

Hello!

Consider the following code:

def create_class(class_name, superclass, &block)
    klass = Class.new superclass, &block
    Object.const_set class_name, klass
end

After I do:

create_class('User', ActiveRecord::Base)

the following is ok:

Object.send(:remove_const, :User)

but this:

Object.remove_const :User

results in this:

NoMethodError: private method `remove_const' called for Object:Class

? Does not make sense for me... can 'send' override Ruby's access checks? Please help!

+4  A: 

It looks like it does override Ruby's access checks.

http://joshstaiger.org/archives/2006/12/the_ruby_send_h.html

My guess is that you would like to play nicely with things other people have made private. If you need to use send to call methods of a class you did not create, you should probably call obj.respond_to on it first.

Oliver N.
looks like it... thanks! by the way, do you how can 'remove_const' be _sanely_ called, i.e., which other method calls it?
sardaukar
A quick google search reveals this: http://www.java2s.com/Code/Ruby/Reflection/Callremoveconsttoremoveaclassdefinition.htmI haven't tried it, so it could be wrong. Also, you may want to change the title of your question to something like "send allows access to private variables" so that it can be more easily searched for.
Oliver N.