国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

ruby元編程實(shí)際使用實(shí)例

2019-10-26 19:23:47
字體:
供稿:網(wǎng)友

很喜歡ruby元編程,puppet和chef用到了很多ruby的語言特性,來定義一個(gè)新的部署語言。
分享幾個(gè)在實(shí)際項(xiàng)目中用到的場景,能力有限,如果有更優(yōu)方案,請(qǐng)留言給我:)

rpc接口模板化——使用eval、alias、defind_method

require 'rack/rpc'class Server < Rack::RPC::Server def hello_world  "Hello, world!" end rpc 'hello_world' => :hello_worldend

上面是一個(gè)rpc server,編寫一個(gè)函數(shù),調(diào)用rpc命令進(jìn)行注冊(cè)。

采用define_method、eval、alias方法,可以實(shí)現(xiàn)一個(gè)判斷rpc/目錄下的*.rb文件,進(jìn)行加載和rpc接口注冊(cè)的功能,實(shí)現(xiàn)代碼如下:

module RPC  require 'rack/rpc'  #require rpc/*.rb文件  Dir.glob(File.join(File.dirname(__FILE__), 'rpc', "*.rb")) do |file|   require file  end  class Runner < Rack::RPC::Server   #include rpc/*.rb and regsiter rpc call   #eg. rpc/god.rb  god.hello   @@rpc_list = []   Dir.glob(File.join(File.dirname(__FILE__), 'rpc', "*.rb")) do |file|    rpc_class = File.basename(file).split('.rb')[0].capitalize    rpc_list = []        #加載module下的方法到Runner這個(gè)類下面    eval "include Frigga::RPC::#{rpc_class}"    #獲取聲明的RPC接口    eval "rpc_list = Frigga::RPC::#{rpc_class}::RPC_LIST"    rpc_list.each do |rpc_name|     #alias一個(gè)新的rpc方法,叫old_xxxx_xxxx     eval "alias :old_#{rpc_class.downcase}_#{rpc_name} :#{rpc_name}"     #重新定義rpc方法,添加一行日志打印功能,然后再調(diào)用old_xxxx_xxxx rpc方法     define_method "#{rpc_class.downcase}_#{rpc_name}".to_sym do |*arg|      Logger.info "[#{request.ip}] called #{rpc_class.downcase}.#{rpc_name} #{arg.join(', ')}"      eval "old_#{rpc_class.downcase}_#{rpc_name} *arg"     end      #注冊(cè)RPC調(diào)用     rpc "#{rpc_class.downcase}.#{rpc_name}" => "#{rpc_class.downcase}_#{rpc_name}".to_sym     #添加到全局變量,匯總所有的rpc方法     @@rpc_list << "#{rpc_class.downcase}.#{rpc_name}"    end   end      def help    rpc_methods = (['help'] + @@rpc_list.sort).join("/n")   end   rpc "help" => :help  end end #RPC

完成上述功能后,可以非常方便的開發(fā)rpc接口,例如下面這個(gè)IP地址增、刪、查的代碼,注冊(cè)ip.list, ip.add和ip.del方法:

module RPC  module Ip   #RPC_LIST used for regsiter rpc_call   RPC_LIST = %w(list add del)   def list    $white_lists   end      def add(ip)     if ip =~ /^((25[0-5]|2[0-4]/d|[0-1]?/d/d?)/.){3}(25[0-5]|2[0-4]/d|[0-1]?/d/d?)$/     $white_lists << ip     write_to_file     return "succ"    else     return "fail"    end   end   def del(ip)    if $white_lists.include?(ip)     $white_lists.delete ip     write_to_file     return "succ"    else     return "fail"    end       end   def write_to_file     File.open(IP_yml, "w") do |f|      $white_lists.uniq.each {|i| f << "- #{i}/n"}     end   end  end  end            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 永胜县| 麦盖提县| 清苑县| 贵德县| 嘉善县| 临高县| 安乡县| 唐山市| 纳雍县| 巴林右旗| 白沙| 辽阳县| 石阡县| 梓潼县| 澄江县| 资兴市| 安西县| 宜良县| 临澧县| 南昌县| 盐城市| 肃南| 宜兰县| 柳江县| 大洼县| 建始县| 贵定县| 且末县| 莱州市| 乌鲁木齐市| 若尔盖县| 金门县| 习水县| 疏勒县| 左云县| 乌鲁木齐县| 安龙县| 班戈县| 阜宁县| 龙江县| 曲阜市|