2011-10-24 54 views
1

我想知道如何構建一個替代開關/外殼的Ruby on Rails設計。如何編寫驗證器模式?

switch (needle) { 
     case 'hello' : 
      // some operation 
      return "something" 
      break; 

     case 'world' : 
      // some operation 
      return "something" 
      break; 

     default : 
      return "default"; 
      break; 
    } 

我在考慮代表驗證器的不同類。有這樣的模式嗎?

class hello 
    def validate 
    // validate something 
    end 
def execute 
    // do something 
    end 
end 

class world 
    def validate 
    // validate something 
    end 
def execute 
    // do something 
    end 
end 

class implementation 
    def main 
    validate(hello, world) 
    end 
end 
+2

對你正在嘗試做一些更多的信息準確,將有助於 – zsquare

+0

我只是想用字符串檢查不同的東西。例如。用indexOf() – fabian

回答

0

您可以在Rails中創建自己的自定義驗證類。請參閱http://juixe.com/techknow/index.php/2006/07/29/rails-model-validators/

然後,您只需在模型中使用它們。

另外還有未被充分利用的模式:

# string with square brackets and a regexp, returning the first match or nil 
"fred"[/d/] 

你可以有一些有趣的這個東西拉出來的字符串和使用它們作爲消息,但被警告調試這種事情可以是一個噩夢。

你真的只是試圖發送一個任意的消息到一個對象嗎?在這種情況下,send()將做到這一點。

0

你可以這樣做:

class MyClass 
    def my_method my_valitation_str 
    validator = Validator.from_str validation_str 
    validator.validate 
    end 

    class Validator 
    class Hello 
     def self.str 
     "hello" 
     end 
     def validate 
     ... the hello validation code 
     end 
    end 
    class World 
     def self.str 
     "world" 
     end 
     def validate 
     ... the hello validation code 
     end 
    end 
    def self.validator_types 
     [Hello, World] 
    end 

    def self.from_str val_str 
     validator_types.select{|t| t.str == val_str}.first 
    end 
    end 
end 

使用嵌套類是完全以可選。

但是在大多數情況下你不需要使用類。Validator類可以是一個模塊。而from_str可以直接返回模塊。

其實,如果「驗證」是指在一個MyClass的實例進行操作,比你可以用返回的模塊擴展類...