如何解析和转储 Ruby 配置文件?
How to parse and dump Ruby config files?
在 this 博客 post 中,他给出了 Ruby 配置文件的示例。
config do
allow ['server.com', `hostname`.strip]
vhost 'api.server.com' do
path ‘/usr/local/api’
end
vhost 'www.server.com' do
path '/usr/local/web'
end
%w{wiki blog support}.each do |host|
vhost "#{host}.server.com" do
path "/usr/local/#{host}"
end
end
end
我想到了加载配置文件后的散列,但也许这不是此类配置的用途...
更新
如果我执行它,我得到
$ ruby config.rb
config.rb:2:in `<main>': undefined method `config' for main:Object (NoMethodError)
问题
解析和转储此配置文件的内容需要哪些 Ruby 代码?
该配置示例不能直接加载,如果我对博客 post 作者的理解是正确的,那么它也不意味着 loading/parsing 该示例没有简单的方法。
关键部分在博客 post 中,他指出 "build simple DSLs to design semantically robust config files without the underlying ruby being conspicuous"(我的重点)。 'underlying ruby' 我指的是启用您看到的 DSL 元素的代码,例如 'config' 和 'vhost'。
然而,您最初的问题是,加载该配置需要什么代码 - 下面是一些可行的示例,完整的实现取决于您,而且我敢肯定还有更干净的代码,"better" 相同的方法。
class AppConfig
attr_accessor :hosts
def allow(hosts)
@hosts = hosts
end
def vhost(hostname)
end
def process_config(&block)
instance_eval(&block)
end
end
def config(&block)
config = AppConfig.new
config.process_config &block
puts "Hosts are: #{config.hosts}"
end
load 'config.rb'
在 this 博客 post 中,他给出了 Ruby 配置文件的示例。
config do
allow ['server.com', `hostname`.strip]
vhost 'api.server.com' do
path ‘/usr/local/api’
end
vhost 'www.server.com' do
path '/usr/local/web'
end
%w{wiki blog support}.each do |host|
vhost "#{host}.server.com" do
path "/usr/local/#{host}"
end
end
end
我想到了加载配置文件后的散列,但也许这不是此类配置的用途...
更新
如果我执行它,我得到
$ ruby config.rb
config.rb:2:in `<main>': undefined method `config' for main:Object (NoMethodError)
问题
解析和转储此配置文件的内容需要哪些 Ruby 代码?
该配置示例不能直接加载,如果我对博客 post 作者的理解是正确的,那么它也不意味着 loading/parsing 该示例没有简单的方法。
关键部分在博客 post 中,他指出 "build simple DSLs to design semantically robust config files without the underlying ruby being conspicuous"(我的重点)。 'underlying ruby' 我指的是启用您看到的 DSL 元素的代码,例如 'config' 和 'vhost'。
然而,您最初的问题是,加载该配置需要什么代码 - 下面是一些可行的示例,完整的实现取决于您,而且我敢肯定还有更干净的代码,"better" 相同的方法。
class AppConfig
attr_accessor :hosts
def allow(hosts)
@hosts = hosts
end
def vhost(hostname)
end
def process_config(&block)
instance_eval(&block)
end
end
def config(&block)
config = AppConfig.new
config.process_config &block
puts "Hosts are: #{config.hosts}"
end
load 'config.rb'