2012-09-26 59 views
1

我使用類的結構來實現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" 
+1

上面,你有沒有以任何方式是指「模塊MyLib」而不是「方法MyLib」?另外,可選地,您可能需要忘記Java,才能更高效地使用Ruby編碼器:)我不知道它是否僅僅是我,或者Javaisms在這裏聞起來:) –

回答

1

我會做它有點像這樣:

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" 
+0

我很佩服你沒有懶得真的寫Ruby的方式這樣做:) –

+0

謝謝你非常糊塗! –