Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何编写验证程序模式?_Ruby On Rails_Ruby_Design Patterns - Fatal编程技术网

Ruby on rails 如何编写验证程序模式?

Ruby on rails 如何编写验证程序模式?,ruby-on-rails,ruby,design-patterns,Ruby On Rails,Ruby,Design Patterns,我想知道如何构建RubyonRails设计来替换交换机/机箱 switch (needle) { case 'hello' : // some operation return "something" break; case 'world' : // some operation return "something" b

我想知道如何构建RubyonRails设计来替换交换机/机箱

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

您可以在Rails中创建自己的自定义验证类。看

然后你只需要在你的模型中使用它们

还有未充分利用的模式:

# string with square brackets and a regexp, returning the first match or nil
"fred"[/d/]
您可以从字符串中提取内容并将其用作消息,但请注意,调试此类内容可能是一场噩梦


您真的只是想向对象发送任意消息吗?在这种情况下,
send()
将起作用。

您可以执行以下操作:

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
使用嵌套类完全是可选的

但在大多数情况下,您不需要使用类。。验证器类可以是一个模块。并且从_str可以直接返回模块


实际上,如果“validate”要在MyClass实例上操作,那么您可以使用返回的模块扩展该类…

关于您正试图执行的操作的更多信息会有所帮助,我只想用字符串检查不同的内容。例如,使用indexOf()