侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

ruby元编程实际使用实例

技术  /  管理员 发布于 6年前   348

很喜欢ruby元编程,puppet和chef用到了很多ruby的语言特性,来定义一个新的部署语言。
分享几个在实际项目中用到的场景,能力有限,如果有更优方案,请留言给我:)

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

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

上面是一个rpc server,编写一个函数,调用rpc命令进行注册。

采用define_method、eval、alias方法,可以实现一个判断rpc/目录下的*.rb文件,进行加载和rpc接口注册的功能,实现代码如下:

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这个类下面    eval "include Frigga::RPC::#{rpc_class}"    #获取声明的RPC接口    eval "rpc_list = Frigga::RPC::#{rpc_class}::RPC_LIST"    rpc_list.each do |rpc_name|     #alias一个新的rpc方法,叫old_xxxx_xxxx     eval "alias :old_#{rpc_class.downcase}_#{rpc_name} :#{rpc_name}"     #重新定义rpc方法,添加一行日志打印功能,然后再调用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      #注册RPC调用     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

完成上述功能后,可以非常方便的开发rpc接口,例如下面这个IP地址增、删、查的代码,注册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

DSL――使用instance_eval

instance_eval是ruby语言中的瑞士军刀,特别是支持DSL方面。
我们来看一下chef(一个开源的自动化部署工具)中设置文件模板的API:
复制代码 代码如下:
    template "/path/to/file.conf" do
      source "file.conf.erb"
      owner  "wilbur"
      mode   "0744"
    end

上述代码中,source、owner、mode需要从外部block,传递到template内部的block中,为了实现该目的,采用了instance_eval代码如下:

  class ChefDSL   def template(path, &block)    TemplateDSL.new(path, &block)   end  end  class TemplateDSL   def initialize(path, &block)    @path = path    instance_eval &block   end   def source(source); @source = source; end   def owner(owner);  @owner = owner; end   def mode(mode);   @mode  = mode;  end  end

上面这个小技巧使得TemplateDSL对象可以应用block,和在自己的scope一样。block可以访问和调用TemplateDSL中的变量和方法。

如果没有使用instance_eval,如下面的代码,ruby就会抛出一个NoMethodError,因为source、owner、mode无法在block中被访问到。
复制代码 代码如下:
    class TemplateDSL
      def initialize(path, &block)
        @path = path
        block.call
      end
    end

当然也可以使用yeild传递变量的方式实现,但没有instance_eval简洁和灵活。

命令行交互――使用instance_eval

命令行交互,可以采用highline这个gem.
但highline在有些方面不能满足我的需求,比如类似上面介绍的chef template功能,达到的效果如下,大大简化了重复代码:
复制代码 代码如下:
        #检查frigga fail,询问是否继续
        Tip.ask frigga_fail? do
          banner "Check some frigga failed, skip failed host and continue deploy?"
          on :yes
          on :quit do
            raise Odin::TipQuitExcption
          end
        end
        ...

        #运行时显示结果如下:
        Check some frigga failed, skip failed host and continue deploy? [yes/quit]
        #输入yes继续,输入quit退出

实现代码如下:

 require 'colorize' class Tip  def self.ask(stat = true, &block)   new(&block).ret if stat == true  end  attr_reader :ret  def initialize(&block)   @opt = []   @caller = {}   @banner = ""   @ret = false   self.instance_eval(&block)   print "#{@banner} [#{@opt.join('/')}]: ".light_yellow   loop do    x = gets.chomp.strip.to_sym    if @opt.include?(x)     @ret = ( @caller[x].call if @caller.key?(x) )     if @ret == :retry      print "\n#{@banner} [#{@opt.join('/')}]: ".light_yellow      next     else      return @ret     end    else     print "input error, please enter [#{@opt.join('/')}]: ".light_yellow    end   end  end  def on(opt, &block)   @opt << opt   @caller[opt] = block if block_given?  end  def banner(str)   @banner = str  end end


  • 上一条:
    Lua中table的一些辅助函数介绍
    下一条:
    HTML5语义化元素你真的用对了吗
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    • 2025-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客