在铁轨中
例如,
user = User不,
user = User.all有谁知道给变量分配模型名的意义吗?
发布于 2014-07-03 10:54:46
在Ruby中,类名是指向类实例的常量变量。如果您执行类似于user = User的操作,那么您可以调用所有用户的类方法,例如#new、#name.
当需要在类之间动态选择时,将类名存储在变量中可能很有用。
profile = params[:user_type] == "user" ? User : Admin
profile.new(params[:user])另一个有用的场景是为模块内嵌套的长类名创建别名:
# MyModule::NestedModule::MyLongNamedClass
# is a class with class methods that we're going to use a lot
MyClass = MyModule::NestedModule::MyLongNamedClass
MyClass.classMethod1
MyClass.classMethod3
MyClass.classMethod2发布于 2014-07-03 09:47:31
代码的目的之一是在许多类中使用相同的接口。
例如:
eating = Time.now.hour == 13 ? Lunch : Nosh
# We drink tee not depending on weather Lunch, Breakfast or Nosh we have
eating.create(tea: 'with sugar') 如果我们使用STI http://railscasts.com/episodes/394-sti-and-polymorphic-associations,可能会很有用。
它也是一种名为抽象工厂pattern的设计模式
https://stackoverflow.com/questions/24549967
复制相似问题