Search code examples
rubymetaprogrammingaccess-specifier

Send allows access to private variables


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!


Solution

  • 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.