If I want to add a method to the String class in Sinatra, where to put it?

Hi guys. I want to extend the String class method in Sinatra, in the erb file, do something like

<%= 'some string'.my_method %> 

but I do not know how to put the definition code:

 String.class_eval do def my_mythod some_code end end 

By the way, I use the modular coding style of the sinatra

+4
source share
2 answers

I usually use this code in my own file under the lib / ext folder. You can then request this file from your Sinatra application.

In lib / ext / string.rb:

 class String my_mythod some_code end end 

Then add the following to your Sinatra application, assuming your base class file is inside the lib folder:

 require File.dirname(__FILE__) + '/ext/string' 

I would be interested to know what people think about it.

0
source

seems to work wherever I put it (is this a good observation?) anywhere that is evaluated on script start

put it in the application class along with all other fields and methods

should work in a helper class

0
source

All Articles