My app has a model called items, and items has a row called title. I use
the titles in the url, but also other places in my views, in the page
title, etc.
Since I use the titles in the url, I have a before_save method that
strips out any unfriendly characters and converts spaces to underscores,
etc.
I made a helper (which I called gstring) that does a gsub to convert the
underscores back to spaces, but it seems like I have to type
gstring(item.title) a lot!
I tried to add a method to my item model called “title” that does the
gsub to convert the underscores to spaces, but that gives me a “Stack
level too deep” error. Like this:
def title
self.title = self.title.gsub("_", " ")
end
It works if I instead call it something like title_with_spaces but I am
trying to type less and not have to think about it.
Another solution that would make some sense to me would be if I could
add my helper as a string modifier so I could use item.title.pretty but
I am not sure how to add a helper or method that works that way. If I do
that I would like .pretty to be available across all models in all of my
views.
I know if I get this working, that I would then have to treat the titles
differently (re-convert to use the underscores) when I use them in a
link_to, but I am going to use a helper for the link_tos anyways, so
that isn’t a big deal.
I am trying to avoid changing everything around so that I store them in
the db with the spaces, then only add the underscores when I use them in
links, as I already have a lot of them in the db with underscores, and
it affects more of my rows than just titles, I am just using that as an
example here.