我使用类的结构来实现cli脚本。
我想创建类方法来注册一个命令。 当注册一个命令时,我想为它自动生成一个getter。Ruby - 如何在ClassMethod和实例之间共享数据
所以,我有这样的结构:文件的
lib/my_lib/commands.rb
lib/my_lib/commands/setup_command.rb
然后内容:
# lib/my_lib/commands.rb
method MyLib
method Commands
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def register_command(*opts)
command = opts.size == 0 ? {} : opts.extract_options!
...
end
def register_options(*opts)
options = opts.size == 0 ? {} : opts.extract_options!
...
end
end
class AbstractCommand
def name
...
end
def description
...
end
def run
raise Exception, "Command '#{self.clas.name}' invalid"
end
end
end
end
# lib/my_lib/commands/setup_command.rb
module MyLib
module Commands
class SetupCommand < AbstractCommand
include MyLib::Commands
register_command :name => "setup",
:description => "setup the application"
def run
puts "Yeah, my command is running"
end
end
end
end
那我想:
# my_cli_script
#!/usr/bin/env ruby
require 'my_lib/commands/setup_command'
command = MyLib::Commands::SetupCommand.new
puts command.name # => "setup"
puts command.description # => "setup the application"
puts command.run # => "Yeah, my command is running"
上面,你有没有以任何方式是指“模块MyLib”而不是“方法MyLib”?另外,可选地,您可能需要忘记Java,才能更高效地使用Ruby编码器:)我不知道它是否仅仅是我,或者Javaisms在这里闻起来:) –