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')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值