Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make instance methods private in runtime

I need to make some instance methods private after registering that object in another object.

I don't want to freeze the object because it must remain editable, only with less functionality. And I don't want to undef the methods since they are used internally.

What I need is something like:

class MyClass

  def my_method
    puts "Hello"
  end

end

a = MyClass.new
b = MyClass.new

a.my_method                            #=> "Hello"
a.private_instance_method(:my_method)
a.my_method                            #=> NoMethodError
b.my_method                            #=> "Hello"

Any ideas?

like image 929
Filipe Miguel Fonseca Avatar asked Jan 31 '10 13:01

Filipe Miguel Fonseca


1 Answers

You can call method private on the method name anytime to make it private:

>> class A
>> def m
>> puts 'hello'
>> end
>> end
=> nil
>> a = A.new
=> #<A:0x527e90>
>> a.m
hello
=> nil
>> class A
>> private :m
>> end
=> A
>> a.m
NoMethodError: private method `m' called for #<A:0x527e90>
    from (irb):227
    from /usr/local/bin/irb19:12:in `<main>'

or, from outside the class:

A.send :private, :m
like image 127
Mladen Jablanović Avatar answered Sep 18 '22 17:09

Mladen Jablanović