Ruby on Rails 3 中的类方法——我完全迷失了方向! [英] Class methods in Ruby on Rails 3 — I'm totally lost!

查看:38
本文介绍了Ruby on Rails 3 中的类方法——我完全迷失了方向!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景这里.

在上面的链接中,给出了以下示例:

In the above link, the following example is given:

class << self
  def by_author(author)
    where(:author_id => author.id)
  end
end

除了这种语法对我这样的初学者来说是陌生的——我一直认为类方法是用 def self.my_class_method 定义的——我在哪里可以找到关于类的文档Ruby on Rails 中的方法?

Aside from that syntax being foreign to a beginner like me — I had always thought class methods were defined with def self.my_class_method — where can I find documentation about class methods in Ruby on Rails?

据我所知,类方法总是在类本身上调用 (MyClass.my_class_method),但是如果 Rails 中的类方法是可链接的,那么似乎必须发生其他事情在这里!

As far as I know, class methods are always called on the class itself (MyClass.my_class_method), but if class methods in Rails are chainable, it seems as though something else must be going on here!

我想我对类方法的语法发表评论有点被骗了.我真的在问 Rails 如何使类方法可链接——我了解方法链接的工作原理,但不知道 Rails 如何允许您链接类方法而不实际返回类每个链接"之后的对象本身链中.

I suppose I sort of cheated by making that comment about the syntax for class methods. I'm really asking how Rails makes a class method chainable — I understand how method chaining works, but not how Rails can allow you to chain class methods without actually returning the class object itself after each "link" in the chain.

推荐答案

Ruby 中的类方法实际上只是单例类的成员,并且执行 class <<self 涉及直接打开单例类并添加到其中,无需在每个方法定义中声明它.

Class methods in Ruby are really just members of the singleton class, and doing class << self involves opening the singleton class directly and adding to it, removing the need to declare it in each method definition.

这篇关于 Ruby 单例的文章很好地解释了.

至于可链接的类方法,这不是特定于类方法的东西,第二个方法调用只是在从第一个返回的对象上调用.例如:

As far as class methods being chainable, that isn't something specific to class methods, the second method call is simply called on the object returned from the first. For example:

bar = foo.do_something.do_more

相当于:

tmp = foo.do_something
bar = tmp.do_more

在 Rails 中,这种可链接性最常用于构建 SQL 查询(例如,使用 whereorder 等).这是因为这些方法中的每一个都返回一个 ActiveRecord Relation.

In Rails, this chainability is most often used for building SQL queries (e.g., with where or order, etc.). This is achieved because each of these methods returns an ActiveRecord Relation.

原因

 foo.scoped.my_foo_class_method

作品是因为ActiveRecord::Relation#method_missing 执行以下操作:

works is because of ActiveRecord::Relation#method_missing doing the following:

elsif @klass.respond_to?(method)
  scoping { @klass.send(method, *args, &block) }

检查 ActiveRecord 类是否响应调用的方法,如果是,则调用该方法.

Which checks if the ActiveRecord class responds to the method called, and if so, calls that.

这篇关于Ruby on Rails 3 中的类方法——我完全迷失了方向!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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