开发者

How do I require a partial?

I'm fairly new to Rails and am trying to figure out how to add a method to the String class and have the code in my partial know that the String class has been added to. I'm not sure where I should put the require state开发者_高级运维ment.


lib/monkeypatch.rb

class String
  def some_new_func
    ...
  end
end

app/controllers/application.rb:

require "monkeypatch"

(or, if you only want the monkeypatch for a specific controller, put the require in that controller).

See also: Rails /lib modules and


Having never worked with Rails, I'm not sure if there's a "better" way to do this, but you could do this via the respond_to? method, like this:

# extend String class to add new method
class String
  def some_new_func; end
end

# check to see if a String instance has
# that method available
if "test".respond_to? :some_new_func
  puts "Works!"
else
  puts "Doesn't work."
end

# => "Works!"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜