我正在开发一个 Rails 应用程序,并希望包含“在 Ruby on Rails 中获取主机名或 IP“我问。

我在让它工作时遇到问题。我的印象是我应该在 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 script/console, ,我无法使用 local_ip 根本没有方法。有任何想法吗?

有帮助吗?

解决方案

您还没有描述您如何尝试使用该方法,因此如果这是您已经知道的内容,我提前表示歉意。

除非模块包含在类中,否则模块上的方法永远不会被使用。类的实例方法要求有该类的实例。您可能需要一个类方法。并且文件本身应该被加载,一般通过require语句。

如果文件 getip.rb 中有以下代码,

require 'socket'

class GetIP
  def self.local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true

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

然后你应该能够通过说来运行它:

require 'getip'
GetIP.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 类似,但不是将方法添加为 实例 方法,将它们添加为 班级 方法,像这样:

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

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

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

所以你就可以了:-)

requireinclude 是两个不同的东西。

require 是严格从加载路径加载一次文件。加载路径是一个字符串,这是用于确定文件是否已加载的关键。

include 用于将模块“混合”到其他类中。 include 在模块上调用,并且模块方法作为类的实例方法包含在内。

  module MixInMethods
    def mixed_in_method
      "I'm a part of #{self.class}"
    end
  end

  class SampleClass
    include MixInMethods
  end

  mixin_class = SampleClass.new
  puts my_class.mixed_in_method # >> I'm a part of SampleClass

但很多时候你想要混入的模块并不与目标类在同一个文件中。所以你做了一个 require 'module_file_name' 然后在课堂上你做一个 include module.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top