in rails
例如,
user = User
不
user = User.all
是否有人知道将模型名称分配给变量的含义?
答案 0 :(得分:1)
代码的目的之一是为许多类使用相同的接口 例如:
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
,它可能会有用它也是一个名为Abstract Factory http://en.wikipedia.org/wiki/Abstract_factory_pattern
的设计模式答案 1 :(得分:0)
在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