Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a Rails model file into multiple files (not concerns, not modules, just separate files)?

I have a Rails 4 model Foo defined in a single file foo.rb

# app/models/foo.rb
class Foo < ActiveRecord::Base
  def method1
    ...
  end

  def method2
    ...
  end
end

Without any type of class re-definition (eg, without refactoring to use traits or concerns for example), I would like to simply move some of the code to a new file, 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

When I do so, using the require, it works BUT does not re-load in dev't after changes to the code in that file.

Is there a way to tell Rails to re-load that new file in development after code changes?

like image 350
jpw Avatar asked Nov 19 '25 02:11

jpw


1 Answers

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 = "No such file to load -- %s")

Interprets a file using mechanism and marks its defined constants as autoloaded. file_name can be either a string or respond to to_path.

Common Usage:

Use this method in code that absolutely needs a certain constant to be defined at that point. A typical use case is to make constant name resolution deterministic for constants with the same relative name in different namespaces whose evaluation would depend on load order otherwise.

I typically use require_dependency when developing a class or module that resides in my rails app, perhaps in the lib/ dir. A normal require statement does not reload my changes, so I use require_dependency in files that reference my newly developed class or module.

Source

It should be noted that your miles may vary. Some people experience major slow downs when including a new dependency. I believe this will reload the file every time you call Foo.all, Foo.find(1), etc. So, you should probably only do this in development.

like image 134
Veridian Dynamics Avatar answered Nov 21 '25 18:11

Veridian Dynamics



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!