Search


Meta

Creative


Support


Leesoft

Feed™

Recent Comments

Photos

Oct
27

转载关于Ruby的extend和include

Posted by » developerly
40 hits

Ruby extend and include

from URL: http://www.rsa.idv.tw/?p=151

Ruby modules有兩種方式mixed into a class,讓class可以簡易新增行為

  1. include
  2. 通常用來新增Instance of mehtod

     

     

    module  CMath
    
      def add(n)
    
        self + n
    
      end
    
    end
    
    Fixnum.class_eval do
    
      include CMath
    
    end
    
    puts  3.add 10
  3. extend
  4. 通常用來新增class method

     

     

    module ExtendMe
    
      def v_object_id
    
        “my object id is #{self.object_id}”
    
      end
    
    end
    
    class Person
    
      extend ExtendMe
    
    end
    
    puts Person.v_object_id
  5. extend through include pattern
  6. 提供統一介面處理

     

     

    module ExtendThroughIncludePattern
    
      def self.included(klass)
    
        klass.extend ClassMethods
    
      end
    
      def instance_method
    
        “this is an instance of #{self.class}”
    
      end
    
      module  ClassMethods
    
        def class_method
    
          “this is a method of the #{self} class”
    
        end
    
      end
    
    end
    
    class Person
    
        include ExtendThroughIncludePattern
    
    end
    
    puts Person.new.instance_method
    
    puts Person.class_method

self.included
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.

Oct
21

Racl新鲜出炉:预告

Posted by » developerly
33 hits

今天真的很兴奋,经过这么长时间,终于把Rails程序中权限控制按照我自己的想法实现了。特此留个记号,明天将正式发布我的权限控制插件。欢迎大家交流!