In Ruby on Rails, to extend the String class, where should the code be put in?
I always add a core_ext
directory in my lib
dir.
Create an initializer for loading the custom extensions (for example: config/initializers/core_exts.rb
). And add the following line in it:
Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each {|l| require l }
and have your extension like:
lib/core_ext/string.rb
class String
def capitalize_first
# ...
end
end
How to extend the String class in a command line app?
How about you require it from lib/mongify.rb
like so:
require 'string/extensions.rb'
And then put your code in lib/string/extensions.rb
Let us know the exact undefined method
errors you're getting in case this isn't the solution.
Rails4 where should I put my own extensions for existing library?
Probably lib
.
lib/core_ext
can contain extensions for standard functions, and vendor-named directories under lib
for others.
config/initializers
is another commonly used location.
I'd recommend spending time looking at other projects to find what seems most common and works best for you.
Some links that may be of interest:
- In Ruby on Rails, to extend the String class, where should the code be put in?
- How to include all lib folder?
- http://guides.rubyonrails.org/plugins.html#extending-core-classes
In Rails, how to add a new method to String class?
You can define a new class in your application at lib/ext/string.rb
and put this content in it:
class String
def to_magic
"magic"
end
end
To load this class, you will need to require it in your config/application.rb
file or in an initializer. If you had many of these extensions, an initializer is better! The way to load it is simple:
require 'ext/string'
The to_magic
method will then be available on instances of the String
class inside your application / console, i.e.:
>> "not magic".to_magic
=> "magic"
No plugins necessary.
Extend Hash Class in Rails Application
You could resolve this issue in a few different ways:
Assuming that
hash_extensions.rb
resides underyour_app/lib/extensions
. (It's a good idea to store all extensions in a separate folder), require all extensions inconfig/application.rb
as below:Dir[File.join(Rails.root, "lib", "extensions", "*.rb")].each {|l| require l }
Move
hash_extensions.rb
underconfig/initializers
and it should be automoagically loaded.- Create a folder say
lib
orextensions
underyour_app/app
and movehash_extensions.rb
to it and Rails would take care of loading it.
Rails 6 with Zeitwerk: How to Extend Ruby Core Classes like Date, Time, String etc
As is saying on https://github.com/fxn/zeitwerk#file-structure
loader.push_dir(Rails.root.join("app/models"))
loader.push_dir(Rails.root.join("app/controllers"))
And by Zeitwerk author: https://github.com/rails/rails/issues/37835#issuecomment-560563560
The lib folder does not belong to the autoload paths since Rails 3. @pixeltrix's is the recommended modern idiom if you want to autoload.
Otherwise, lib belongs to $LOAD_PATH and you can require files in that directory.
We can call push_dir to load the lib subdirectories. My solution:
# config/initializers/zeitwerk.rb
Rails.autoloaders.main.push_dir(Rails.root.join('lib'))
or
# config/application.rb
...
config.autoload_paths += [
Rails.root.join('lib')
]
Then CoreExt::Date
can be auto loaded.
How to extend class Object in Rails?
First, it's cleaner to just reopen the Object class directly:
class Object
def nil_or_empty?
nil? || respond_to?(:empty?) && empty?
# or even shorter: nil? || try(:empty?)
end
end
Second, telling Rails to autoload /lib doesn't mean that the files in /lib will be loaded when your app starts up - it means that when you use a constant that's not currently defined, Rails will look for a file in /lib corresponding to that constant. For example, if you referred to ObjectExtensions in your Rails app code, and it wasn't already defined somewhere, Rails would expect to find it in lib/object_extensions.rb.
Since you can't extend a core class in /lib like this, it's a better idea to put core extensions in your config/initializers directory. Rails will load all the files in there automatically when your app boots up. So try putting the above Object extension in config/initializers/object_extension.rb, or config/initializers/extensions/object.rb, or something similar, and everything should work fine.
Good practice -- Should helper methods for strings extend the string class?
I find extending built-in objects like that confusing. You move from project to project and wonder why you cannot do my_var.foo only to realize that foo was a function that your colleague wrote.
Just imagine you added extension methods indiscriminately. Now you have to copy a block of code from one project to another and spend time scratching your head about the extension methods.
Related Topics
Ruby, Difference Between Exec, System and %X() or Backticks
Ruby: How to Post a File Via Http as Multipart/Form-Data
How to Match All Occurrences of a Regex
How to Create a Deep Copy of an Object in Ruby
Why Does Installing Nokogiri on MAC Os Fail With Libiconv Is Missing
How to Get a Specific Output Iterating a Hash in Ruby
Ruby'S File.Open and the Need For F.Close
Get Names of All Files from a Folder With Ruby
Double Colons Before Class Names in Ruby
Cannot Load Such File - Zlib Even After Using Rvm Pkg Install Zlib
Difference Between Class Variables and Class Instance Variables
How to Modify Path For Homebrew
Converting a Nested Hash into a Flat Hash
Pass Variables to Ruby Script Via Command Line