Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Object::private and Object::public in Ruby?

What are these methods and how bad is it to override them?

irb(main):001:0> Object::respond_to?('private', true)
=> true

irb(main):002:0> Object::respond_to?('public', true)
=> true

The problem comes up in Rails when trying to define a scope named private or public for a model. Because of the fix for bug https://rails.lighthouseapp.com/projects/8994/tickets/4167-activerecord-named_scope-using-columns-as-the-name-is-buggered now there's a lot of warnings like:

Creating scope :public. Overwriting existing method MyModel.public.
like image 232
Ivan Kuznetsov Avatar asked Oct 05 '11 08:10

Ivan Kuznetsov


People also ask

What is private in Ruby?

Private: – When a method is declared private in Ruby, it means this method can never be called with an explicit receiver. Any time we're able to call a private method with an implicit receiver.

What is private and protected in Ruby?

protected methods can be called by any instance of the defining class or its subclasses. private methods can be called only from within the calling object. You cannot access another instance's private methods directly.

What is public method Ruby?

What are public methods in Ruby? Public methods are methods that allow objects to interact with each other. The set of public methods of the object creates its interface. The more expressively defined such methods the easier it's to use the object.

What are objects called in Ruby?

In Ruby, we call them methods because everything is an object and all functions are called on objects. All methods are functions, but the reverse isn't necessarily true. "Hello world!" is an instance of the class String .


1 Answers

The public and private methods are actually ruby's access modifiers.

Basically, when you do this:

class Example
  public

  def something
  end

  private

  def something_else
  end
end

The public and private keywords are actually not keywords at all, they're method calls. I'm pretty sure it's not a good idea to override them, so I'd name the scopes in some other way.

like image 168
Andrew Radev Avatar answered Oct 13 '22 02:10

Andrew Radev