2012-06-15 70 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,所以具有相同名稱的類不會發生衝突(所以它與mixin無關)。這是標準的。

爲什麼我們將自己追加到課堂,這是不是已經暗示?

這只是defining class-methods(另一個是​​)的方法之一。

+0

特別感謝命名空間鏈接。 –

11

這是否與包含模塊相同?

號當你有module Foo; end,然後做

class Bar 
    include Foo 
end 

你結束了一個類Bar包括模塊Foo的所有方法。但是,當我們做

module Foo 
    class Bar 
    end 
end 

我們結束了一個類Foo::Bar包括沒有一種方法Foo不在Bar

什麼是做這種方式的優勢在哪裏?

它允許你組織你的代碼,如果需要的話。

爲什麼我們將自己追加到課堂,這是不是已經暗示?

不,它不是「暗示」的。這樣做相當於用self.(如def self.mymethod; end)定義該塊中的每個方法。請參閱class << self idiom in Ruby