gpt4 book ai didi

ruby-on-rails - 向 Rails 添加功能

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:28 24 4
gpt4 key购买 nike

我正在开发 Rails 应用程序,并希望包含我要求的“Getting the Hostname or IP in Ruby on Rails”中的一些功能。

我在使用它时遇到了问题。我的印象是我应该只在 lib 目录中创建一个文件,所以我将其命名为“get_ip.rb”,内容为:

require 'socket'

module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily

UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end

我也曾尝试将 GetIP 定义为一个类,但是当我执行通常的 ruby 脚本/控制台 时,我根本无法使用 local_ip 方法。有什么想法吗?

最佳答案

require 将加载一个文件。如果该文件包含任何类/模块定义,那么您的其他代码现在就可以使用它们。如果该文件仅包含不在任何模块中的代码,它将像在您的“require”调用(如 PHP include)相同的位置一样运行

include 与模块有关。

它获取模块中的所有方法,并将它们添加到您的类中。像这样:

class Orig
end

Orig.new.first_method # no such method

module MyModule
def first_method
end
end

class Orig
include MyModule
end
Orig.new.first_method # will now run first_method as it's been added.

还有 extend,它的工作方式与 include 类似,但不是将方法添加为 instance 方法,而是将它们添加为 class 方法,例如这个:

注意上面,当我想访问 first_method 时,我如何创建一个 Orig 类的新对象。这就是我所说的实例方法的意思。

class SecondClass
extend MyModule
end
SecondClass.first_method # will call first_method

请注意,在这个例子中我没有创建任何新对象,只是直接在类上调用方法,就好像它一直被定义为 self.first_method 一样。

到此为止:-)

关于ruby-on-rails - 向 Rails 添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253/

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