这个 Ruby 类方法如何被调用? [英] how does this Ruby class method get invoked?

查看:36
本文介绍了这个 Ruby 类方法如何被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 rails 应用程序导出 CSV 的屏幕截图中,Ryan Bates 展示了以下简单代码.

In a screen cast on Exporting CSV from a rails app, Ryan Bates presented the following simple code.

我试图弄清楚 Product::to_csv 类方法实际上是如何在 ProductController.rb 的第 5 行调用的,因为它似乎不遵循正常的 Ruby 规则.

I'm trying to figure out how the class method Product::to_csv actually gets invoked on line 5 of ProductController.rb, as it doesn't seem to follow the normal Ruby rules.

product.rb

1 class Product < ActiveRecord::Base   
2   def self.to_csv(options = {})
3     ...
4   end
5 end

products_controller.rb

1 class ProductsController < ApplicationController
2  def index
3    @products = Product.order(:name)
4    respond_to do |format|
5      format.csv { send_data @products.to_csv }
6      ...
7    end
8  end
9 end

由于 to_csv 是一个类方法,我希望调用看起来像 Product::to_csv().

Since to_csv is a class method, I'd expect the invocation to look like Product::to_csv().

根据文档,@products 是 ActiveRecord::Relation 的一个实例.为什么发送到 ActiveRecord::Relation 实例的消息会导致 Product 类对象上的方法被调用?更奇怪的是,在发送方和接收方中将 to_csv 重命名为任意名称会导致 NoMethodError,所以也许有一些基于以 to_ 开头的名称的魔法?

According to the documentation, @products is an instance of ActiveRecord::Relation. Why do messages sent to an instance of ActiveRecord::Relation cause methods on the Product class object to get invoked? To make it even stranger, renaming to_csv to some arbitrary name in both the the sender and receiver leads to NoMethodError, so maybe there is some magic afoot based on names that begin with to_?

我是否遗漏了一些明显的东西?任何澄清将不胜感激.

Am I missing something obvious? Any clarification would be greatly appreciated.

推荐答案

这只是 Rails 所做的事情之一.任何类方法都会自动作为集合"方法可用,这意味着它们可用于关系对象.作用域和类方法可以这样互换.

This is just one of the things Rails does. Any class methods automatically become available as "collection" methods, meaning they are available to the relation objects. Scopes and class methods are interchangeable that way.

这篇关于这个 Ruby 类方法如何被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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