从Ruby类中调用方法?(或者这是铁路魔术)

Ala*_*orm 2 ruby ruby-on-rails callback

我是Ruby的新手并且正在学习一些教程/截屏视频.我已经到达了他们讨论before_filter回调的部分,并且它使用了一些对我来说有点奇怪的语法.我不知道它是否是红宝石的一个特征,如果它是一些铁轨魔法,并希望有人在这里可以让我直接或指向我正确的方向w/r/t手册

这是我正在观看的截屏视频的代码片段

class MachinesController < ApplicationController
    #...
    before_filter :login_required, :only => [:report]
    #...    
    def index
        #etc...
    end

    def login_required
        #etc...
    end
end
Run Code Online (Sandbox Code Playgroud)

在rails的上下文中,我理解这before_filter是一个在调用动作login_required时将触发方法的回调report.但是,我不清楚在红宝石的背景下它是什么.在其他语言中,类通常包含在大括号内定义的方法,属性,类变量和常量.

但是,这看起来像是在类中的函数调用,并且一些实验表明您可以将代码放入类定义中并在程序运行时调用它.它是否正确?如果是这样,是否有特殊的上下文规则用于将内联放入类中的代码?(即,rails中的before_filter函数是否知道它是从哪个类调用的)如果不是,那么rails在这里做了什么魔术?

Sar*_*Mei 5

before_filter is a not actually a callback. It's a class method of ActiveRecord::Base that sets up a callback when you call it. So in this example:

before_filter :login_required, :only => [:report]
Run Code Online (Sandbox Code Playgroud)

When the class is loaded, the method is called, and it adds :login_required to the filter chain for the report method.

这些类型的调用的约定是删除parens,但它可以正常工作(并且可以更容易识别为方法调用),如果你这样做:

before_filter(:login_required, :only => [:report])
Run Code Online (Sandbox Code Playgroud)