# Пример, который демонстрирует загрузку из файла описания некоторого
# сервиса, которое хранится в следующем формате:
#
# {service
# {name <str>}
# {ips <nonspace>+ }
# [{message <nonspace>
# [{priority <int>}]
# [{field
# {name <str>}
# {type <nonspace>}]*
# }]*
# }
#
# Например:
# {service
# {name "DayTime"}
# {ips localhost:3028 my.site.org:5000 }
# {message GetCurrentTime}
# {message GetUTCTime
# {priority 0}
# {field {name "localTime"} {type String}}
# {field {name "timeZone"} {type String}}
# }
# }
#
# Формат запуска примера:
# ruby -Ilib examples/service_description.rb <description-file>
#
require 'cls-ruby'
require 'cls-ruby/tag_no_value'
require 'cls-ruby/tag_scalar'
require 'cls-ruby/tag_scalar_vector'
require 'cls-ruby/tag_vector_of_tags'
module ServiceDescriptionExample
# Описание одного поля сообщения.
Field = Struct.new( :name, :type )
# Описание одного сообщения.
Message = Struct.new( :name, :priority, :fields )
# Описание сервиса.
Service = Struct.new( :name, :ips, :messages )
# Функция загрузки описания из указанного файла.
#
# :call-seq:
# load_cfg_file( file_name ) => Service
#
def ServiceDescriptionExample.load_cfg_file( file_name )
tag = Impl::TagService.new
ClsRuby::parse_file( file_name, tag )
tag.value
end
# Реализация тегов в описании сервиса.
module Impl
# Класс тега {field}.
#
class TagField < ClsRuby::TagNoValue
mandatory_child_tag :name, ClsRuby::TagStringScalar
mandatory_child_tag :type, ClsRuby::TagScalar,
:format => ClsRuby::SCALAR_NONSPACE_STRING
default_tag_params :name => 'field'
def value
Field.new( @name.value, @type.value )
end
end
# Класс тега {message}.
#
class TagMessage < ClsRuby::TagScalar
child_tag :priority, ClsRuby::TagIntScalar
child_tag :field, ClsRuby::TagVectorOfTags, :type => TagField
default_tag_params :name => 'message',
:format => ClsRuby::SCALAR_NONSPACE_STRING
def value
Message.new(
super,
@priority.tag_defined? ? 0 : @priority.value,
@field.collect_values_by( :value ) )
end
end
# Класс тега {service}
#
class TagService < ClsRuby::TagNoValue
mandatory_child_tag :name, ClsRuby::TagStringScalar
mandatory_child_tag :ips, ClsRuby::TagScalarVector,
:format => ClsRuby::SCALAR_NONSPACE_STRING
child_tag :message, ClsRuby::TagVectorOfTags,
:type => TagMessage
default_tag_params :name => 'service'
def value
Service.new(
@name.value,
@ips.value,
@message.collect_values_by( :value ) )
end
end
end # module Impl
end # module ServiceDescriptionExample
ARGV.each do |file_name|
s = ServiceDescriptionExample.load_cfg_file( file_name )
puts "#{file_name}: #{s}"
end
# vim:ts=2:sts=2:sw=2:expandtab:ft=txt:tw=78
Generated with the Darkfish Rdoc Generator 2.