Make instance methods private in runtime

ε祈祈猫儿з 提交于 2019-12-07 06:12:10

问题


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?


回答1:


What's public and what's private is per class. But each object can have its own class:

class Foo

  private

  def private_except_to_bar
    puts "foo"
  end

end

class Bar

  def initialize(foo)
    @foo = foo.dup
    class << @foo
      public :private_except_to_bar
    end
    @foo.private_except_to_bar
  end

end

foo = Foo.new
Bar.new(foo)    # => "foo"

foo.private_except_to_bar
# => private method `private_except_to_bar' called for #<Foo:0xb7b7e550> (NoMethodError)

But yuck. Consider these alternatives:

  • Just make the method public.
  • Explore alternative designs.



回答2:


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



回答3:


class A
  def test
    puts "test"
  end
  def test2
    test
  end
end

a = A.new

class << a
  private :test
end

a.test2 # works
a.test  # error: private method


来源:https://stackoverflow.com/questions/2171743/make-instance-methods-private-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!