首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

Ruby 动态特征鉴赏

2013-12-29 
Ruby 动态特性鉴赏以下代码与代码学习来自Ruby Best Practives,主要描述了一幅生动的Ruby语言动态特性使

Ruby 动态特性鉴赏

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

#!/usr/bin/env ruby## encoding: utf-8## Base module NativeCampingRoutesmodule 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)    endendmodule 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    endendNativeCampingRoutes.process('/hello',:name=>'greg')NativeCampingRoutes.process('/goodbye',:name=>'joe')

?

热点排行