开发者

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

开发者 https://www.devze.com 2023-03-21 05:59 出处:网络
I want to expand a method to the String class in Sinatra, in the erb file, do somet开发者_如何学编程hing like

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

0

精彩评论

暂无评论...
验证码 换一张
取 消