내가 할 것 : 파일의
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
내가 원하는
그래서,이 구조 그것은 어쨌든 다음과 같습니다 :
class CommandDummy
def self.register_command(options = {})
define_method(:name) { options[:name] }
define_method(:description) { options[:name] }
end
register_command :name => "setup",
:description => "setup the application"
def run
puts "Yeah, my command is running"
end
end
c = CommandDummy.new
puts c.name # => "setup"
puts c.description # => "setup the application"
추가 대신 opts.size == 0
의
당신이 사용할 수 opts.empty?
편집 : 그냥 어떤 방법으로, 코드에서 위의 약간
# NOTE: I've no idea where to use stuff like this!
class CommandDummy
# Add methods, which returns a given String
def self.add_method_strings(options = {})
options.each { |k,v| define_method(k) { v } }
end
add_method_strings :name => "setup",
:description => "setup the application",
:run => "Yeah, my command is running",
:foo => "bar"
end
c = CommandDummy.new
puts c.name # => "setup"
puts c.description # => "setup the application"
puts c.run # => "Yeah, my command is running"
puts c.foo # => "bar"
연주를했다
"MyLib"대신 "module MyLib"을 의미합니까? 또한 선택적으로 Ruby 코더가 더 효율적으로 작동하도록 Java를 취소해야 할 수도 있습니다 :) 만약 내가 단지 나인지 또는 Javaism이 여기에서 냄새를 맡을 지 모르겠다. :) –