msn email google-talk twitter tumblr flickr

如何组织你的类

某老外推荐的组织结构

   1      #define the class
   2      class MyClass
   3      #attr_accessor are really public instance methods, but
   4      #they are getter/setters, so its probably better just to put them up top
   5      att_accessor :some_instance_attr
   6  
   7      #some activesupport love here..
   8      #this is a singlton method that sets up your class level
   9      #getter/setter for @@some_class_attr
  10      cattr_accessor :some_class_attr    
  11  
  12      #class methods go in this section.  I prefer to use the class << self block
  13      #instead of writing self. in front of every method.
  14      class<<self
  15        # this is a class method which can be called like this:
  16        # MyClass.name #=> "MyClass"
  17        def name
  18          "MyClass"
  19        end
  20      end
  21  
  22      #public instance methods go in this section.  These methods are available
  23      #to any instance of MyClass.  Example:
  24      #my = MyClass.new
  25      #my.test #=> "test"
  26      public
  27        def test
  28          "test"
  29        end   
  30  
  31        #this public instance method is used by the protected method.. see below
  32        def access_protect_method
  33          self.protect_me
  34        end
  35  
  36        #this public instance method is used by the private method.. see below
  37        def access_private_method
  38          private_parts
  39        end
  40  
  41      # protected methods are available to
  42      # self (or an object with the same class as self).  Example:
  43      # m = MyClass
  44      # m.access_protect_method #=> "thanks for protecting me"
  45      # but you can't call it directly from the instance like this
  46      # m.protect_me #=>ruby no likey.. this ain't public boy
  47      # you probably will not use protected often..
  48      protected
  49        def protect_me
  50          "thanks for protecting me"
  51        end
  52  
  53      # this is locked down.. but not as tight as java.. subclasses still have access
  54      # if you try to call with self.private_parts, you will get an error.  Do it this way:
  55      # m = MyClass.new
  56      # m.private_access_method #=> "only implicit calls can touch my private parts"
  57      private
  58        def private_parts
  59          "only implicit calls can touch my private parts"
  60        end
  61      end#class end