我在单个文件foo.rb中定义了Rails 4模型Foo
# app/models/foo.rb
class Foo < ActiveRecord::Base
def method1
...
end
def method2
...
end
end
在没有任何类型的类重新定义的情况下(例如,无需重构即可使用特征或关注点),我想简单地移动一些代码到新文件foo_more.rb中
# app/models/foo.rb
require File.expand_path('../foo_more.rb', __FILE__)
class Foo < ActiveRecord::Base
def method1
...
end
end
# app/models/foo_more.rb
class Foo < ActiveRecord::Base
def method2
...
end
end
当我这样做时,使用require可以工作,但是在该文件中的代码更改后BUT不会重新加载到dev'中。
有没有办法告诉Rails在代码更改后重新加载开发中的新文件?
答案 0 :(得分:1)
require_dependency File.expand_path('../foo_more.rb', __FILE__)
class Foo < ActiveRecord::Base
def method1
...
end
end
# app/models/foo_more.rb
class Foo < ActiveRecord::Base
def method2
...
end
end
require_dependency(file_name,message =“没有要加载的文件- %s“)
使用机制解释文件并标记其定义 自动加载的常量。 file_name可以是字符串或响应 到to_path。
常用用法:
在绝对需要一定常量的代码中使用此方法 在这一点上定义。典型的用例是使常量名称 确定具有相同相对名称的常量的分辨率 不同的命名空间,其评估将取决于加载顺序 否则。
在开发驻留在我的rails应用程序(可能是lib / dir)中的类或模块时,我通常使用require_dependency。普通的require语句不会重新加载更改,因此我在引用我新开发的类或模块的文件中使用require_dependency。
请注意,您的里程可能会有所不同。当包含新的依赖项时,有些人会遇到严重的问题。我相信这将在您每次调用Foo.all
,Foo.find(1)
等时重新加载文件。因此,您可能应该只在开发中这样做。