代码之家  ›  专栏  ›  技术社区  ›  Chris Bunch

向Rails添加功能

  •  2
  • Chris Bunch  · 技术社区  · 16 年前

    我正在开发一个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 script/console ,我无法使用 local_ip 方法完全如此。有什么想法吗?

    3 回复  |  直到 10 年前
        1
  •  4
  •   Curt Hagenlocher    16 年前

    你还没有描述你是如何使用这个方法的,所以如果这是你已经知道的东西,我提前道歉。

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

    如果以下代码在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
    
        2
  •  5
  •   Orion Edwards    16 年前

    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 do,但不是将方法添加为 实例 方法,添加为 方法,如:

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

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

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

    那你就去:—)

        3
  •  0
  •   the Tin Man    10 年前

    require include 是两件不同的事情。

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

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

      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 .