Ruby类使用静态方法调用私有方法吗? [英] Ruby class with static method calling a private method?

查看:93
本文介绍了Ruby类使用静态方法调用私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有许多静态方法的类。每个人都必须调用一个通用方法,但我尝试不公开后一种方法。将其设为私有只会允许从自己的类实例进行访问吗?受保护似乎也不能解决问题。

I have a class with a number of static methods. Each one has to call a common method, but I'm trying not to expose this latter method. Making it private would only allow access from an own instance of the class? Protected does not seem like it would solve the problem here either.

如何隐藏do_calc使其在静态上下文中不被外部调用? (让它可以从头两个静态方法中调用。)

How do I hide do_calc from being called externally in a static context? (Leaving it available to be called from the first two static methods.)

class Foo
  def self.bar
    do_calc()
  end
  def self.baz
    do_calc()
  end
  def self.do_calc
  end
end


推荐答案

首先,静态并不是 Ruby行话的真正组成部分。

First off, static is not really part of the Ruby jargon.

让我们举一个简单的例子:

Let's take a simple example:

class Bar
  def self.foo
  end
end

它定义了方法 foo 放在显式对象 self 上,该对象在该范围内返回包含类 Bar
是的,可以将其定义为 class方法,但是 static 在Ruby中实际上没有意义。

It defines the method foo on an explicit object, self, which in that scope returns the containing class Bar. Yes, it can be defined a class method, but static does not really make sense in Ruby.

然后 private 不起作用,因为在显式对象上定义方法(例如 def self.foo

Then private would not work, because defining a method on an explicit object (e.g. def self.foo) bypasses the access qualifiers and makes the method public.

您可以做的是使用 class<<。 self 语法来打开包含类的元类,并将其中的方法定义为实例方法:

What you can do, is to use the class << self syntax to open the metaclass of the containing class, and define the methods there as instance methods:

class Foo
  class << self

    def bar
      do_calc
    end

    def baz
      do_calc
    end

    private

    def do_calc
      puts "calculating..."
    end
  end
end

这将为您提供所需的内容。

This will give you what you need:

Foo.bar
calculating...

Foo.baz
calculating...

Foo.do_calc
NoMethodError: private method `do_calc' called for Foo:Class

这篇关于Ruby类使用静态方法调用私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆