Ruby 动态特性鉴赏

以下代码与代码学习来自<Ruby Best Practives>,主要描述了一幅生动的Ruby语言动态特性使用场景。

#!/usr/bin/env ruby
#
# encoding: utf-8
#

# Base module NativeCampingRoutes
module NativeCampingRoutes

    # This is a convenient way to make instance methods into class methods.
    # And you can use this method to make a singleton.
    # http://ozmm.org/posts/singin_singletons.html
    # 将成员对象方法上升为类方法
    extend self

    def R(url)
        route_lookup = routes
        # Get a class-object
        klass = Class.new

        # Modify the meta-class-object(klass)
        # Extend the modules' methods to klass
        meta = class << klass; self; end


        #meta class, overwrite the define_method
        #The following block will be called by Class.instance_eval
        meta.send(:define_method, :inherited) do |base|
            raise "Already defined" if route_lookup[url]
            route_lookup[url] = base
        end

        klass
    end

    def routes
        @routes ||= {}
    end

    def process(url, params={})
        routes[url].new.get(params)
    end
end

module NativeCampingRoutes

    #R '/hello'
    #   will create a class-object which has been overwrited the define_method
    class Hello < R '/hello'
        #This will be invoked by overwrited method(define_method)
        def get(params)
            puts "hello #{params[:name]}"
        end
    end
    class Goodbye < R '/goodbye'
        def get(params)
            puts "goodbye #{params[:name]}"
        end
    end
end

NativeCampingRoutes.process('/hello',:name=>'greg')
NativeCampingRoutes.process('/goodbye',:name=>'joe')

 

你可能感兴趣的:(dynamic,Ruby)