Forgive me if this is a really stupid question, I’ve only started
learning Rails.
After some Googling and talking to some people, I still don’t know how
to do this.
Basically, what I want to do is to be able to create a class that I
can use anywhere in my application, kind of like the way you can use a
method anywhere when you define it in the ApplicationHelper module.
Specifically, I don’t like using methods like truncate(string, length)
and h(string), and I’d much rather use them in the form of
string.truncate(length) and string.h(),
Could anybody tell me how to do this? Thanks in advance.
Basically, what I want to do is to be able to create a class that I
can use anywhere in my application, kind of like the way you can use a
method anywhere when you define it in the ApplicationHelper module.
as of that:
You should be able to created your class under the lib directory.
Specifically, I don’t like using methods like truncate(string, length)
and h(string), and I’d much rather use them in the form of
string.truncate(length) and string.h(),
Could anybody tell me how to do this? Thanks in advance.
if you want to define a method for an object (instance method), you’ll
need to define that in that instance’s class; so, if you want to play
around with strings, you’ll need to modify that class.
class String
def truncate(size)
self[0…size]
# self is the instance being worked on
end
end