gpt4 book ai didi

ruby-on-rails - RoR 的 "magic"命名空间解析是如何工作的?

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:23 25 4
gpt4 key购买 nike

我从使用 Python 开始,我对 Ruby on Rails 的“魔力”是如何工作的感到非常困惑。

<强>1。任何地方都没有 require 语句

在 Python 中,为了从任何地方访问函数,您必须导入。我认为基础 ruby 也是如此。但是当使用 rails 时,我可以调用在其他模块中定义的隐藏变量和函数,而无需在页面顶部添加任何 require 语句。

例如我可以有一个这样的文件:

class CartsController < ApplicationController
....
def show
begin
@cart = Cart.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to store_url, notice: 'Invalid cart'
end
end

loggerredirect 等都没有定义。它是简单地从 ApplicationController 继承一些复杂的树,还是通过其他机制以某种方式访问​​这些命名空间?

<强>2。使用不存在的方法

这是有效的 Rails 代码

current_item = line_items.find_by_product_id(product_id)

find_by_products_id 尚未在任何地方定义,但 Rails 以某种方式动态地动态“创建”了该方法。关于如何做到这一点的任何技术见解?

感谢您的帮助!

最佳答案

Rails 的“魔法”广泛使用了 method_missingconst_missing

当您尝试调用未定义的方法时,ruby 会触发对method_missing 的调用。ActiveRecord 等库使用它来实现动态查找器。

method_missing 示例:

SomeModel.find_by_some_field("some_value") 未定义。

这会调用 SomeModel.method_missing(:find_by_some_field, "some_value")

ActiveRecord 然后将此调用转换为`SomeModel.where(:some_field => "some_value")

(出于性能目的,ActiveRecord 然后动态定义此方法,因此下次定义find_by_some_field)

const_missing 示例:

SomeModel 尚未被要求。

Ruby 解释器使用参数 "SomeModel"调用 const_missing

Rails 遵循约定 "SomeModel" 应该在名为 some_model.rb 的文件中定义,所以 const_missing 只是尝试 require "some_model”

关于ruby-on-rails - RoR 的 "magic"命名空间解析是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14387654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com