Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby on Rails, to extend the String class, where should the code be put in?

If on Ruby on Rails, I need to add a method called

class String   def capitalize_first     # ...   end end 

and wonder where should the file go to? (which directory and filename, and is any initialize code needed?) This is for a Rails 3.0.6 project.

like image 765
nonopolarity Avatar asked Apr 13 '11 19:04

nonopolarity


People also ask

How do you extend a string class?

You cannot extend a class that is marked as final. You can use composition to either put a String object inside or you can hand roll your own version. This can be accomplished via character arrays and the other magic that goes into creating String classes.

How does Ruby on Rails work?

Rails combines the Ruby programming language with HTML, CSS, and JavaScript to create a web application that runs on a web server. Because it runs on a web server, Rails is considered a server-side, or “back end,” web application development platform (the web browser is the “front end”).

What is a Rails application?

Rails is a web application development framework written in the Ruby programming language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks.


1 Answers

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 
like image 123
Mike Lewis Avatar answered Sep 19 '22 16:09

Mike Lewis