在类主体中声明的 Ruby 方法调用 [英] Ruby Method calls declared in class body

查看:39
本文介绍了在类主体中声明的 Ruby 方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在 Rails 上学习 ruby​​,我遇到过如下代码:

I have just started learning ruby on rails and I have encountered code like below:

class Post < ActiveRecord::Base
 validates_presence_of   :title
 belongs_to :user
end

类体内有两个方法调用.我很难找到任何 ruby​​ 文档描述从类的主体内部(但在任何方法外部)调用方法的工作方式.我所有的书,只描述了如何定义类和实例方法以及如何从其他方法中调用它们.

There are two method calls inside the class body. I have had a hard time finding any ruby documentation that describes how method calls from within a body of a class (but outside of any method) work. All the books I have, only describe how to define class and instance methods and how to call them from within other methods.

我的问题是:如何以及何时调用这些方法?它们是如何定义的?它们是在某个活动记录模块中定义的吗?

The questions I have are: How and when are these methods called? How are they defined? Are they mixins defined in some active record module?

推荐答案

类定义的主体是代码的执行上下文,就像其他任何上下文一样.那里的代码在类的上下文中执行(意思是 self 是类对象,它是 Class 的一个实例).您可以拥有局部变量和实例变量(它们属于类对象本身而不是类的实例),并且您可以调用类对象响应的任何方法.代码在类定义块完成后运行.

The body of a class definition is an execution context for code just like any other. Code there is executed within the context of the class (meaning self is the class object, which is an instance of Class). You can have locals and instance variables (which will belong to the class object itself rather than instances of the class) and you can call any method that class object responds to. The code is run once the class definition block is finished.

在这种情况下,ActiveRecord::Base 定义了类方法 validates_presence_ofbelongs_to.

In this case, ActiveRecord::Base defines the class methods validates_presence_of and belongs_to.

这篇关于在类主体中声明的 Ruby 方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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