2012-06-15 4 views
8

작업 코드를 측량 (Surveyor라고하는 모듈에서, 그 이상은 아닙니다), 이해하려고합니다. 모듈 내의 클래스를 포함하는이 섹션을 살펴 보았습니다. 이것은 모듈을 포함하는 것과 동일합니까? 그렇지 않다면 이런 식으로하는 것의 이점은 무엇입니까? 감사. (보너스 포인트 : 우리는 클래스에 자신을 추가하는 이유는, 이미 암시하지 않는 것이 무엇입니까?)모듈 내에서 클래스 선언하기

module Surveyor 
    class Common 
    RAND_CHARS = [('a'..'z'), ('A'..'Z'), (0..9)].map{|r| r.to_a}.flatten.join 
    OPERATORS = %w(== != < > <= >= =~) 

    class << self 
     def make_tiny_code(len = 10) 
     if RUBY_VERSION < "1.8.7" 
      (1..len).to_a.map{|i| RAND_CHARS[rand(RAND_CHARS.size), 1] }.join 
     else 
      len.times.map{|i| RAND_CHARS[rand(RAND_CHARS.size), 1] }.join 
     end 
     end 

     def to_normalized_string(text) 
     words_to_omit = %w(a be but has have in is it of on or the to when) 
     col_text = text.to_s.gsub(/(<[^>]*>)|\n|\t/su, ' ') # Remove html tags 
     col_text.downcase!       # Remove capitalization 
     col_text.gsub!(/\"|\'/u, '')     # Remove potential problem characters 
     col_text.gsub!(/\(.*?\)/u,'')     # Remove text inside parens 
     col_text.gsub!(/\W/u, ' ')      # Remove all other non-word characters  
     cols = (col_text.split(' ') - words_to_omit) 
     (cols.size > 5 ? cols[-5..-1] : cols).join("_") 
     end 

     def equal_json_excluding_wildcards(a,b) 
     return false if a.nil? or b.nil? 
     a = a.is_a?(String) ? JSON.load(a) : JSON.load(a.to_json) 
     b = b.is_a?(String) ? JSON.load(b) : JSON.load(b.to_json) 
     deep_compare_excluding_wildcards(a,b) 
     end 
     def deep_compare_excluding_wildcards(a,b) 
     return false if a.class != b.class 
     if a.is_a?(Hash) 
      return false if a.size != b.size 
      a.each do |k,v| 
      return false if deep_compare_excluding_wildcards(v,b[k]) == false 
      end 
     elsif a.is_a?(Array) 
      return false if a.size != b.size 
      a.each_with_index{|e,i| return false if deep_compare_excluding_wildcards(e,b[i]) == false } 
     else 
      return (a == "*") || (b == "*") || (a == b) 
     end 
     true 
     end 

     alias :normalize :to_normalized_string 

     def generate_api_id 
     UUIDTools::UUID.random_create.to_s 
     end 
    end 
    end 
end 

답변

15

이런 식으로 일을의 장점은 무엇인가?

이 이름은 namespace입니다. 따라서 같은 이름의 클래스는 충돌하지 않습니다 (따라서 mixins와는 아무런 관련이 없습니다). 표준입니다.

우리는 왜 수업에 스스로 추가합니까? 아직 암시되지 않았습니까?

그 방법은 단지 defining class-methods (다른 하나는 def self.method_name 임) 중 하나 일뿐입니다.

+0

네임 스페이스 링크에 대한 추가 감사. –

11

모듈 포함과 동일합니까?

번호는 module Foo; end이 다음

class Bar 
    include Foo 
end 

당신은 모듈 Foo의 모든 메소드를 포함하는 클래스 Bar와 끝까지 않습니다. 그러나 우리는 우리가 이런 식으로 일을의 장점은 무엇 Bar

에없는 그 Foo의 방법 중 어느 것도 포함되지 않습니다 클래스 Foo::Bar로 끝날

module Foo 
    class Bar 
    end 
end 

을 수행 할 때?

필요하면 코드를 구성 할 수 있습니다.

우리는 왜 수업에 스스로 추가합니까? 아직 암시되지 않았습니까?

아니요, 아직 "암시되지 않았습니다." 이렇게하면 해당 블록의 각 메서드를 self. (def self.mymethod; end)으로 정의하는 것과 같습니다. class << self idiom in Ruby을 참조하십시오.

관련 문제