gpt4 book ai didi

ruby-on-rails - 来自rails类内部模块的未定义函数错误

转载 作者:行者123 更新时间:2023-12-04 16:37:49 25 4
gpt4 key购买 nike

我有一个 module Helper 存在于 app/models/concerns/helper.rb

module Helper
def func
return ['A', 'B', 'C']
end
end

我有一个 NewService 类,它存在于 app/services/pqr/new_service.rb

module PQR
class NewService < ApplicationService
include Helper
@@results = func

def self.another_func
if @@results.blank?
@@results = func
end
end
end
end

关于调用函数:PQR::NewService.another_func
我收到错误:(PQR::NewService:Class 的未定义局部变量或方法 func)

Ruby version - 2.5.3
Rails version - 5.2.3

最佳答案

你正在类范围内调用 func;为什么您希望从那里可以访问实例范围的方法?这是您代码的 MCVE

class Foo
def func; end # instance method
func # class scope
end

要使 func 可访问,应使其在类级别可用。这意味着,您应该将您的问题包含在 PQRsingleton_class 中。

人为的例子:

module Foo
def func; puts "YO"; end
end

class Bar
class << self
include Foo
end

func
end

关于ruby-on-rails - 来自rails类内部模块的未定义函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58534128/

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