knoopx
knoopx

Reputation: 17400

How do I dynamically define a method as private?

This does not seem to work:

class Test
  private

  define_method :private_method do 
    "uh!"
  end
end

puts Test.new.private_method

Upvotes: 14

Views: 9668

Answers (3)

Henrik N
Henrik N

Reputation: 16274

It seems that starting with Ruby 2.1, define_method respects private:

$ rvm 2.1.0
$ ruby /tmp/test.rb
/tmp/test.rb:10:in `<main>': private method `private_method' called for #<Test:0x00000102014598> (NoMethodError)
$ rvm 2.0
$ ruby /tmp/test.rb
uh!

(I realize this is an old question, but I happened across it via Google.)

Upvotes: 10

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

Module#private takes an optional argument for the method name:

class Test
 private :private_method
end

The above is of course equivalent to

Test.private :private_method # doesn't work

Except that Module#private is private, so you have to use reflection to circumvent the access restrictions:

Test.send :private, :private_method

No eval necessary.

Upvotes: 7

Brian Campbell
Brian Campbell

Reputation: 332836

Test.instance_eval { private :private_method }

Or, just run

private :private_method

from within the Test class.

Upvotes: 37

Related Questions