`
biyeah
  • 浏览: 202932 次
  • 来自: ...
社区版块
存档分类
最新评论

[转]Method visibility in Ruby

    博客分类:
  • Ruby
 
阅读更多
From:http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby
A common point of confusion to even experienced Ruby programmers is the visibility of public, protected, and private methods in Ruby classes. This largely stems from the fact that the behavior of those keywords in Ruby is different from what you might have learned from Java and C.

To demonstrate these differences, let’s set up a little script:


class Foo
  def a; end

  # call 'a' with explicit 'self' as receiver
  def b; self.a; end

  # call 'a' with implicit 'self' as receiver
  def c; a; end
end

def safe_send(receiver, method, message)
  # can't use 'send' because it bypasses visibility rules
  eval "receiver.#{method}"
rescue => e
  puts "#{message}: #{e}"
else
  puts "#{message}: succeeded"
end

visibility = ARGV.shift || "public"
Foo.send(visibility, :a)

foo = Foo.new
safe_send(foo, :a, "explicit receiver       ")
safe_send(foo, :b, "explicit 'self' receiver")
safe_send(foo, :c, "implicit 'self' receiver")

Basically, the script just creates a class “Foo” with three methods: a, which we’ll invoke directly with an explicit, non-self receiver; b, which invokes a with self as receiver, and c, which invokes a with an implicit receiver of self. We’ll use the safe_send method to call each of those methods and log the result.

So, first: the public keyword. In Ruby, public means that the method may be invoked just about any way you please; in technical terms, the receiver of the message may be either explicit (“foo.bar”), self (“self.bar”) or implicit (“bar”).

引用
$ ruby demo.rb public
explicit receiver       : succeeded
explicit 'self' receiver: succeeded
implicit 'self' receiver: succeeded

The protected keyword puts a straitjacket around the method. Any method declared protected may only be called if the receiver is self, explicitly or implicitly. (Update: protected methods may actually be called any time the receiver is of the same class as ‘self’...and an explicit self as receiver is just a specific case of that. Modifying the script to demonstrate this condition is left as an exercise for the reader.)

引用
$ ruby demo.rb protected
explicit receiver       : protected method `a' called for #<Foo:0x3fc18>
explicit 'self' receiver: succeeded
implicit 'self' receiver: succeeded

Lastly, the private keyword is the tightest setting of all. A private method cannot be called with an explicit receiver at all, even if that receiver is “self”.

引用
$ ruby demo.rb private
explicit receiver       : private method `a' called for #<Foo:0x3fc18>
explicit 'self' receiver: private method `a' called for #<Foo:0x3fc18>
implicit 'self' receiver: succeeded

Note that, unlike languages such as Java, inheritance plays absolutely no part in determining method visibility in Ruby. Subclasses can access both protected and private methods of the superclass without trouble, so long as they abide by the rules laid out above.

The difference between protected and private is very subtle, as you can see, which explains why protected is rarely used by most Rubyists. If it is used at all, it is generally as a convention, to document methods that are internal to the class, but which lie closer to the public interface than others. In Rails, for instance, you might declare your controller filter methods and model validation methods as “protected” (because the framework will call those methods) and reserve the “private” designation for those methods that are only ever called from within your own model or controller code.
分享到:
评论

相关推荐

    Modeling Mutual Visibility Relationship in Pedestrian Detection

    Modeling Mutual Visibility Relationship in Pedestrian Detection Modeling Mutual Visibility Relationship in Pedestrian Detection Modeling Mutual Visibility Relationship in Pedestrian Detection

    Visibility_in_Bad_Weather_from_A_Single_Image

    ### 基于单张图像的恶劣天气下能见度增强技术 #### 概述 在计算机视觉领域,恶劣天气条件如雾、霾等对场景可见性的显著降解是一个重大挑战。这种现象从光学角度来看,主要是由于大气中存在的大量粒子吸收和散射...

    WPF的bool2Visibility转换器使用

    `BoolToVisibilityConverter` 是一个内置的数据转换器,它用于将布尔值(`bool`)转换为 `Visibility`枚举类型,这对于根据逻辑状态控制UI元素的可见性非常有用。在本教程中,我们将深入探讨如何使用`...

    Hierarchical Visibility in Terrains

    **层次可见性(Hierarchical Visibility)**是一种优化技术,主要用于提高三维地形渲染的效率。它通过预先计算和存储不同层次上的可见性信息来减少实际渲染时的计算量,从而实现更快的渲染速度。这种技术特别适用于...

    VIsibility属性

    VISIBILITY属性详解 在 Android 开发中,控件的可见性是非常重要的,VISIBILITY 属性就是控制控件的显示和隐藏的。通过设置 VISIBILITY 属性,我们可以控制控件的可见性,达到不同的显示效果。 VISIBLE、INVISIBLE...

    Android中visibility属性

    在Android开发中,`visibility`属性是控制UI组件可见性的重要元素,广泛应用于各种视图控件,如TextView、ImageView、Button等。该属性决定了一个控件是否在屏幕上显示,以及如何显示。`visibility`属性有三个可能的...

    Sensor Fusion Method for Horizon Detection From an Aircraft in Low Visibility

    基于多传感器融合的低能见度下飞机水平线检测方法 在现代航空领域,飞机在低能见度条件下的进近和着陆始终是一个高度关注的课题。尽管已经设计并使用了各种先进设备来提高操纵飞机的安全阈值,低能见度依然是潜在的...

    DataGrid_Column_Visibility_Binding

    return (value is Visibility visibility) && visibility == Visibility.Visible; } } ``` 接下来,你需要在你的XAML资源字典中声明这个转换器: ```xml ``` 这里的`local`是命名空间前缀,需要根据实际...

    display与visibility的区别

    ### Display与Visibility的区别 在网页布局与样式设计中,`display`与`visibility`属性是控制元素显示状态的两种常用方式。尽管它们都能达到隐藏或显示元素的目的,但两者之间存在本质的区别。本文将深入探讨这两种...

    前端项目-visibility.js.zip

    《前端项目中的Page Visibility API与visibility.js库》 在当今的Web开发中,前端性能优化是不可或缺的一部分。其中,理解用户与页面的交互状态对于提升用户体验至关重要。这就是Page Visibility API和`visibility....

    「DDoS」Gaining Endpoint Log Visibility in ICS Environments - 法

    在工业控制系统(ICS)环境中,确保网络安全至关重要,尤其是在面临分布式拒绝服务(DDoS)攻击时。本文将深入探讨如何在ICS环境下提升终端日志的可见性,以更好地防范潜在的安全威胁,符合法律法规的要求。...

    JS中style.display和style.visibility的区别实例说明.docx

    JS 中 style.display 和 style.visibility 的区别实例说明 在 JavaScript 中,style.display 和 style.visibility 是两种常用的控制元素显隐的方法,但是它们之间有着根本的区别。 style.display style.display ...

    Method for enhancing visibility of hazy images based on polarimetric imaging

    A novel polarimetric dehazing method is proposed based on three linear polarization images (0°, 45°, and 90°). The polarization orientation angle of the light scattered by the haze particles is ...

    使用CSS3 backface-visibility属性制作3D翻转动画效果.zip

    本教程将详细讲解如何利用CSS3的`backface-visibility`属性来创建3D翻转动画效果。这个属性是实现高级动画和过渡效果的关键,特别是在构建响应式和动态用户界面时。 `backface-visibility`属性主要用于控制元素在3D...

    对比: display, visibility(有代码)

    在网页设计和开发中,`display` 和 `visibility` 是两个非常重要的CSS属性,它们用于控制元素在页面上的可见性和布局。这篇博客文章通过代码示例深入探讨了这两个属性的区别和用法。 首先,`display` 属性主要用于...

    satellite visibility_satellite_卫星轨道计算

    "satellite visibility_satellite_卫星轨道计算"这个标题暗示我们要讨论的是如何预测和计算卫星在特定地点的可见性,这对于地面站接收信号或者规划卫星任务来说是极其关键的。 首先,卫星的轨道是由它的六根数(也...

    CSS隐藏元素 display visibility opacity的区别.docx

    在CSS中,隐藏元素的方法主要有三种:`display:none`、`visibility:hidden`和`opacity:0`,它们各自有不同的特点和适用场景。 1. `display:none`:此属性会使元素完全从页面布局中消失,不占据任何空间。元素及其...

Global site tag (gtag.js) - Google Analytics