0
votes

I'm trying to extend the String class in my Rails 4.2 app. I created a lib/string.rb file to hold the extensions.

class String
  def testing
    "testing"
  end
end

I added lib to autoload_paths in application.rb.

config.autoload_paths << Rails.root.join('lib')

When I startup the rails console and execute "".testing, I get NoMethodError: undefined method 'testing' for "":String

Can anyone explain why this method isn't getting picked up? I have a hunch that it's because the String constant is already loaded, so Rails doesn't need to autoload the constant. As a result, it never tries to load the lib/string.rb file and my method never gets added to String.

When I explicitly require the file in an initializer, I can get the method loaded, but if I change the method, I have to restart the server to get rails to see the change. It feels like I'm missing something. It seems like there should be a way to get Rails to automatically read core extension classes and reload them when the file changes.

1
I put all of my monkey patches in lib/monkey and add the following to the bottom of application.rb: Dir.glob(Rails.root.join 'lib', 'monkey', '*', '.rb').each {|f| require f} - mockaroodev
Thanks. I ended up creating an initializer with Dir.glob(Rails.root.join 'lib', 'autorequire', '**', '*.rb').each {|f| require f}. This will find all .rb files inside the lib/autorequire directory and all sub directories no matter how deeply nested they are. - CodeSmith

1 Answers

2
votes

Yep, you're right. It will not autoload string since it's already defined. I usually put core class extensions inside an initializer. So config/initializers/string.rb