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 statement.
Asked
Active
Viewed 274 times
0
2 Answers
3
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

Community
- 1
- 1

Wayne Conrad
- 103,207
- 26
- 155
- 191
-
Does there need to be quotes around `monkeypatch`, or does Rails convert `monkeypatch` into a string? – Andrew Grimm Nov 09 '11 at 02:18
-
1@Andrew, Thanks for the gentle reminder that I goofed here. Fixed. – Wayne Conrad Nov 11 '11 at 01:12
2
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!"

Josh Sandlin
- 714
- 8
- 21