从Ruby类中调用方法? (或是这个轨道魔术) [英] Calling a Method from Within a Ruby Class? (or is this rails magic)

查看:98
本文介绍了从Ruby类中调用方法? (或是这个轨道魔术)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ruby的新手,正在开发一些教程/截屏。我到达了他们讨论 before_filter 回调的部分,它使用一些对我来说很奇怪的语法。我不知道这是否是一个红宝石的功能,如果它是一些rails魔术,并希望有人在这里可以设置我直或指向正确的方向w / r / t的手册

I'm new to Ruby and working through some tutorials/screencasts. I've reached the section where they're discusisng the before_filter callback, and it's using some syntax that's a little weird for me. I don't know if it's a feature of ruby, of if it's some rails magic, and was hoping someone here could set me straight or point me in the right direction w/r/t the manual

这是我正在观看的screencast的代码片段

This is a code fragment from the screencast I'm watching

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

    def login_required
        #etc...
    end
end

在rails的上下文中, code> 报告时,将会触发 login_required 动作被调用。然而,我不清楚在ruby的上下文中是什么。在其他语言中,类通常包含在大括号中定义的方法,属性,类变量和常量。

In the context of rails, I understand that before_filter is a callback that will fire login_required method when the report action is called. However, it's not clear to me what it is within the context of ruby. In other languages classes typically contain methods, properties, class variables and constants defined within the braces.

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

However, this looks like its a function call inside the class, and some experiments have show that you can put code in your class definitions and have it called when the program runs. Is this correct? If so, are there special contextual rules for code that's put inline into a class like that? (i.e. would the before_filter function in rails know what class it was called from) If not, what magic is rails doing here?

推荐答案

before_filter 实际上不是一个回调。这是 ActiveRecord :: Base 的类方法, ,在您调用回调时设置回调。所以在这个例子中:

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]

加载类时,将调用该方法,并添加:login_required 报告方法的过滤器链。

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

这些类型的调用的约定是删除括号,但它会工作很好(如果你这样做更容易识别为方法调用):

The convention for these types of calls is to drop parens, but it would work just fine (and would be more easily identifiable as a method call) if you did this:

before_filter(:login_required, :only => [:report])

这篇关于从Ruby类中调用方法? (或是这个轨道魔术)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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