【发布时间】:2016-03-02 12:15:05
【问题描述】:
我是 Ruby 新手,可能不懂一些基本的东西:
我正在尝试这个:
# lib/common_stuff.rb
module CommonStuff
def self.common_thing
# code
@x = second_thing # --> should access method in same module. Doesn't work.
end
def self.second_thing
# code
end
end
# app/controllers/my_controller.rb
require 'common_stuff'
class MyController < ApplicationController
include CommonStuff
y = self.common_thing # accesses the Module method -> works
end
错误:
NoMethodError(未定义的方法 `second_thing' MyController:0x000000088d8990): lib/common.rb:7:in 'common_thing'
我尝试了模块和实例方法。此外,仅将 second_thing 声明为实例方法或 Module 中的两种方法都声明为实例方法是行不通的。我有什么误解?
** 编辑更正**
我意识到我的错误是使方法成为类方法(带有 self. 前缀)。没有它,它实际上是有效的。以为我试过了,但我昨天一定是瞎了。所以工作代码是(只是一个构造的例子——通常我当然不会实例化控制器):
# lib/common_stuff.rb
module CommonStuff
def common_thing
@x = second_thing # --> access method in same module. Works now too.
end
def second_thing
10
end
end
# app/controllers/my_controller.rb
require 'common_stuff.rb'
class MyController
include CommonStuff
def a_class
y = common_thing # accesses the Module method -> works
puts y
end
end
ctrl = MyController.new
ctrl.a_class
【问题讨论】:
-
second thing被定义为类方法,但在您的模块中被调用为实例方法。 -
@harishsr:ruby 中没有“类方法”。每个方法都是一个实例方法(这里的实例是当前
self是什么) -
好的;确实,现在它不再起作用了。我不知道我以前在做什么。在上面的片段中,我忘记在 MyController 类中编写 Method 定义——但这不是问题。所以让我问一下:如果你有两个 Rails 控制器,它们都共享两种方法(其中第二种方法由第一种方法使用)。你会把这两种方法放在哪里?进入一个模块,使用 7stud 的答案中所示的钩子方法,或者可能进入一个关注点?
-
这进一步混淆(注入的钩子似乎没有必要):yehudakatz.com/2009/11/12/better-ruby-idioms
标签: ruby-on-rails ruby