获取Ruby模板的字符串?

时间:2016-12-23 21:30:12

标签: ruby templates erb

在下面的脚本中puts输出

admin1:secretpw@example.com

我需要将其拆分为用户名和密码,因此我可以将其用于模板

[admins]
<%= couchdbAdminUri.user %> = <%= couchdbAdminUri.password %>

问题

如何将couchdbAdminUri变成对象,以便我可以使用上面的模板?

#!/usr/bin/ruby

require 'erb'
require 'yaml'
require 'uri'
require 'awesome_print'

data_root = '/vol'
config_root = File.join(data_root, 'config')

couchdb = YAML::load_file(File.join(config_root, 'couchdb.yaml'))
couchdbAdminUri = URI(couchdb['_admin']['db'])

puts couchdbAdminUri

b = binding
tmp = ERB.new File.read("local.ini.erb"), nil, "%"
File.open("local.ini", "w") do |f|
  f.write(tmp.result(b))
end

1 个答案:

答案 0 :(得分:2)

你可以创建一个类

#!/usr/bin/ruby

require 'erb'
require 'yaml'
require 'uri'
require 'awesome_print'

data_root = '/vol'
config_root = File.join(data_root, 'config')

couchdb = YAML::load_file(File.join(config_root, 'couchdb.yaml'))
result = URI(couchdb['_admin']['db']).split(':')

class CredentialURI
  attr_reader :user, :password
  def initialize(user, pwd)
     @user = user
     @password = pwd
  end
end

user = result.first
password = result.last

couchdbAdminUri = CredentialUri.new(user, password)

b = binding
tmp = ERB.new File.read("local.ini.erb"), nil, "%"
File.open("local.ini", "w") do |f|
  f.write(tmp.result(b))
end