I want to expand a method to the String class in Sinatra, in the erb file, do somet开发者_如何学编程hing like
<%= 'some string'.my_method %>
but I don't know how to put the definition code:
String.class_eval do
def my_mythod
some_code
end
end
By the way I'm using the sinatra modular coding style
I tend to stick code like this in its own file, under the lib/ext folder. Then, you can require this file from your Sinatra app.
Under lib/ext/string.rb:
class String
my_mythod
some_code
end
end
Then add the following to your Sinatra app, assuming your base class file is inside the lib folder:
require File.dirname(__FILE__) + '/ext/string'
I'd be interested to see what over people think on this as well.
seems to work wherever i put it (is this a good observation?) anywhere that is evaluated on script start
drop it in the app class itself along with all the other fields and methods
should work in the helper class too
精彩评论