2013-02-26 2 views
30

Ruby 모듈 (믹스 인)을 사용하려고합니다.루비 : 모듈, 필수 및 포함

#!/usr/bin/env ruby 
require_relative 'lib/mymodule' 

class MyApp 
    include MyModule 
    self.hallo 
end 

및 lib 디렉토리/mymodule.rb :

module MyModule 
    def hallo 
    puts "hallo" 
    end 
end 

아주 간단한 설치

나는 test.rb 있습니다. 하지만 :(작동하지 않습니다?.

ruby test.rb 
test.rb:8:in `<class:MyApp>': undefined method `hallo' for MyApp:Class (NoMethodError) 
     from test.rb:6:in `<main>' 

가 어디에 오류가

답변

53

요약하면 모듈 include 대신 extend이 필요합니다.

class MyApp 
    extend MyModule 
    self.hallo 
end 

include는. 그것을 혼합 클래스에 대한 인스턴스 방법을 제공

extend은 그것을 혼합 클래스에 대한 클래스 메소드를 제공합니다.

this 읽기주세요.

3

귀하의 코드가 작동 -하지만 모듈은 당신이하지 생각하지 않습니다 포함한 모듈을 포함하는 클래스는받지 않습니다 . 방법 - 다음은이 클래스의 뜻에서 객체

그래서이 작동합니다 :

class MyApp 
    include MyModule 
end 

my_app_object = MyApp.new 
my_app_object.hallo # => hallo 

my_app_object는 모듈 인 MyModule의 유지 mixin을 가지고 클래스의 MyApp,의 목적은 T. 모듈과 mixins에 대한 완전한 설명은 there을보십시오.

8

문제는 인스턴스 정의 (include)로 추가하는 동안 클래스 정의에서 hallo을 호출하는 것입니다.

그래서 당신은 하나 extend (hallo 클래스의 방법이 될 것이다) 사용할 수 있습니다

module MyModule 
    def hallo 
    puts "hallo" 
    end 
end 

class MyApp 
    extend MyModule 
    self.hallo 
end 

또는 중 하나를 호출 hallo을 MyApp를의 인스턴스에서 :

module MyModule 
    def hallo 
    puts "hallo" 
    end 
end 

class MyApp 
    include MyModule 
end 

an_instance = MyApp.new 
an_instance.hallo 
1
class MyApp 
    class << self 
    include MyModule 
    end 
    self.hallo 
end 

이 동일하다

class MyApp 
    extend MyModule 
    self.hallo 
end 

extends는 클래스 객체를 열고 모듈 메소드를 포함합니다. "hallo"는 일종의 클래스 객체가됩니다. MyApp 클래스의 정적 메서드

"그래서"개체를 "자기"가 아닌 경우 수신기의 메서드에 메서드를 삽입하십시오. 자신의 경우 "자기"인 방법으로 수신기에 "확장"을 삽입하십시오.

self.include MyModule // inject the methods into the instances of self 
self.extend MyModule // inject the methods into object self 

"self"는 MyApp 클래스 개체를 가리 킵니다.

또한 "include"와 "extend"는 module.rb에 정의 된 메소드 일뿐입니다. "include"는 클래스 개체 메서드 (정적 메서드)이며 "extend"는 인스턴스 메서드입니다.