2012-09-26 2 views
1

cli 스크립트를 구현하기 위해 클래스 구조에서 작업합니다.
그리고 클래스 메서드를 만들어 명령을 등록하고 싶습니다. 명령어를 등록 할 때, 자동으로 getter를 생성하고 싶습니다. Ruby - ClassMethod와 인스턴스간에 데이터를 공유하는 방법

# 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"대신 "module MyLib"을 의미합니까? 또한 선택적으로 Ruby 코더가 더 효율적으로 작동하도록 Java를 취소해야 할 수도 있습니다 :) 만약 내가 단지 나인지 또는 Javaism이 여기에서 냄새를 맡을 지 모르겠다. :) –

답변

1

내가 할 것 : 파일의

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

Ruby 방식을 실제로 쓰는 게 아니라고 감탄했습니다. 그것을해라 :) –

+0

매우 고맙다 고맙습니다! –