[英]Dynamically loading Thor options for a Ruby Gem
While trying to develop a simple gem to learn the process, I happened to stumble on this issue: Thor DSL takes in options to a command using the syntax: option :some_option, :type => :boolean
, just prior to the method definition. 虽然试图开发一个简单的宝石学的过程中,我正好绊倒在这个问题上: 雷神 DSL使用语法如下的选项 命令
option :some_option, :type => :boolean
,只是之前的方法定义。
I am trying to have a dynamic set of options loaded from a file. 我正在尝试从文件中加载一组动态选项。 I do this file read operation in the constructor, but it seems the
option
keyword for the Thor class is getting processed before the initialize
method. 我在构造函数中执行此文件读取操作,但似乎在
initialize
方法之前已处理了Thor类的option
关键字。
Any ideas to resolve this? 有解决这个问题的想法吗? Also it would be great if someone can explain how the option keyword works?
如果有人可以解释option关键字的工作原理,那也将是一件很不错的事情? I mean is
option
a method call? 我的意思是
option
是方法调用吗? I don't get the design. 我没有设计。 (This is the first DSL I am trying out and am a total newbie to Ruby Gems)
(这是我正在尝试的第一个DSL,并且是Ruby Gems的新手)
#!/usr/bin/env ruby
require 'thor'
require 'yaml'
require 'tinynews'
class TinyNewsCLI < Thor
attr_reader :sources
@sources = {}
def initialize *args
super
f = File.open( "sources.yml", "r" ).read
@sources = YAML::load( f )
end
desc "list", "Lists the available news feeds."
def list
puts "List of news feed sources: "
@sources.each do |symbol, source|
puts "- #{source[:title]}"
end
end
desc "show --source SOURCE", "Show news from SOURCE feed"
option :source, :required => true
def show
if options[:source]
TinyNews.print_to_cli( options[:source].to_sym )
end
end
desc "tinynews --NEWS_SOURCE", "Show news for NEWS_SOURCE"
@sources.keys.each do |source_symbol| # ERROR: States that @sources.keys is nil
#[:hindu, :cnn, :bbc].each do |source_symbol| # I expected the above to work like this
option source_symbol, :type => :boolean
end
def news_from_option
p @sources.keys
TinyNews.print_to_cli( options.keys.last.to_sym )
end
default_task :news_from_option
end
TinyNewsCLI.start( ARGV )
After a bit of tweaking, I think I ended upon a solution that doesn't look too bad. 经过一些调整后,我认为我得出了一个看起来还不错的解决方案。 But not sure placing code in module like that is a good practice.
但是不确定将代码放置在这样的模块中是一种好习惯。 But anyways:
但是无论如何:
#!/usr/bin/env ruby
require 'thor'
require 'yaml'
require 'tinynews'
module TinyNews
# ***** SOLUTION *******
f = File.open( "../sources.yml", "r" ).read
SOURCES = YAML::load( f )
class TinyNewsCLI < Thor
default_task :news_from_source
desc "list", "Lists the available news feeds."
def list
puts "List of news feed sources: "
SOURCES.each do |symbol, source|
puts "- #{source[:title]}"
end
end
desc "--source NEWS_SOURCE", "Show news for NEWS_SOURCE"
option :source, :required => true, :aliases => :s
def news_from_source
TinyNews.print_to_cli( options[:source].to_sym )
end
end
end
TinyNews::TinyNewsCLI.start( ARGV )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.