hello world(ruby 代码生成器)

本文介绍了一种利用Ruby语言和ERB模板系统自动生成代码的方法。通过解析JSON配置文件,该方法可以根据不同的输入数据生成特定的SQL插入语句及其他代码文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、编写erb模板

template/sql.erb

<%for organization in data.keys%>insert into org_domain(Domain, organization) values('<%=data[organization]%>','<%=organizatio
n%>');
<%end%>

2、稍微复杂一些的生成器代码

create.rb

#!/usr/bin/env ruby
require "erb"
require 'json'

class Creater
  def proc
    str = IO.read("config.json");
    configs=JSON.parse(str)
    configs.each do |p|
      create(p)
    end
  end
  def create(p)
    Dir.mkdir("dist") unless FileTest.exist?("dist")
    todir = "dist/" +p["name"]
    Dir.mkdir(todir) unless FileTest.exist?(todir)
    Dir.foreach("template") do |file|
      if file !="." and file !=".."
        data = p["data"]
        tofile =File.new(todir+"/"+file, "w")
        fromfile = "template/"+file
        File.open( fromfile ) { |fh|
          e = ERB.new( fh.read )
          tofile.print e.result( binding )
        }
        tofile.close
      end
    end
  end
end
c = Creater.new()
c.proc()

config.json

[{"name":"a","data":{"a":"a","b":"b"}},
{"name":"b","data":{"b":"a","b":"b"}},
{"name":"c","data":{"c":"a","b":"b"}},
{"name":"d","data":{"d":"a","b":"b"}}]

5、执行 ruby creater.rb 
在dist下生成4组代码,后续增加模板,可以实现代码的快速生成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值