Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby private class method helper

Hi I am trying to create a helper for mass defining ruby methods as private class methods. In general one can define a method as a private class method by using private_class_method key work. But I would like to create a helper in the following style:

class Person
  define_private_class_methods do 
    def method_one
    end

    def method_two
    end
  end
end

The way I planned to dynamically define this is in the following way, which is not at all working:

class Object
  def self.define_private_class_methods &block
    instance_eval do
      private
      &block
    end
  end
end

any ideas where I might be going wrong?

like image 310
MIdhun Krishna Avatar asked Apr 20 '17 11:04

MIdhun Krishna


People also ask

Can a class method be private Ruby?

there's no such thing as "a private section" in Ruby. To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie.

How do you call a private method from a class in Ruby?

You need to use "private_class_method" as in the following example. I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance.

How do I make my class method private?

The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.

Can a Ruby module have private methods?

Private instance/class methods for modulesDefining a private instance method in a module works just like in a class, you use the private keyword. You can define private class methods using the private_class_method method.


1 Answers

$ cat /tmp/a.rb

class Object
  def self.define_private_class_methods &cb
    existing = methods(false)
    instance_eval &cb
    (methods(false) - existing).each { |m| singleton_class.send :private, m }
  end
end

class Person
  define_private_class_methods do 
    def method_one
            puts "¡Yay!"
    end
  end
end

Person.send(:method_one)
Person.public_send(:method_one)

$ ruby /tmp/a.rb

¡Yay!

/tmp/a.rb:18:in `public_send': private method `method_one' 
                 called for Person:Class (NoMethodError)
Did you mean?  method
    from /tmp/a.rb:18:in `<main>'

Please note, that it’s hard to understand, what you are trying to achieve and possibly there is better, cleaner and more robust way to achieve this functionality.

like image 173
Aleksei Matiushkin Avatar answered Oct 06 '22 04:10

Aleksei Matiushkin