2012-06-15 146 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