2017-04-21 10 views
1

다음 코드가 아래 오류를 나타내는 이유는 무엇입니까? 내가 Open3::popen3 즉, 전체 경로를 사용하여 popen3를 호출하는 경우모듈을 '포함'하지만 여전히 메서드를 호출 할 수 없습니다.

require 'open3' 

module Hosts 
    def read 
    include Open3 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 

Hosts.read 
#=> undefined method `popen3' for Hosts:Class (NoMethodError) 

그것은 작동합니다. 하지만 include -ed가 있으므로 Open3:: 비트가 필요하지 않다고 생각 했습니까?

감사합니다.

답변

0

인스턴스 메소드를 정의했지만 싱글 톤 메소드로 사용하려고합니다.

module Hosts 
    extend Open3 

    def read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
    module_function :read # makes it available for Hosts 
end 

지금 :

Hosts.read 
## 
# Host Database 
# 
# localhost is used to configure the loopback interface 
# when the system is booting. Do not change this entry. 
## 
127.0.0.1 localhost 
255.255.255.255 broadcasthost 
::1    localhost 
=> nil 

당신을 위해 더 명확하게 일을 할 것입니다 루비에서 다음과 같은 개념에 대해 읽기 : 당신이 할 수 원하는 것을 만들려면, 당신은 또한 extendOpen3하지 include에있는

  • 상황

  • self

  • includeextend

대신 module_fuction 당신은 또한 다음 중 하나와 동일한 결과를 얻을 수 있습니다 :

module Hosts 
    extend Open3 
    extend self 

    def read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 

그리고

module Hosts 
    extend Open3 

    def self.read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 
+0

아, 알았어. 그 줄은 짧지 만. 나는 '연장'을 읽을 것입니다. 그리고 'module_function'! 매우 감사합니다. – spoovy

+0

@spoovy N/p :) 또한 몇 가지 옵션을 추가하여 동일한 효과를 얻을 수 있습니다. 잠시 후에 편집 할 것입니다 (관심이있는 경우에 대비해 :)) –