I have a nice piece of functional and tested Ruby code that I would like to integrate into a rails project:
require 'open-uri'
def shorten(url)
open("http://is.gd/api.php?longurl=#{url}").read
rescue
nil
end
I want to call the method shorten(url) from show.html.erb in the following way:
<% @shorturl = shorten("http://www.google.com/search?q=#{@bands.item.gsub(' ', '+')}+san+francisco") %>
I thought that placing the method shorten, within the model would work but it results in a NoMethodError (the require ‘open-uri’ is placed in the application_controller.rb)
undefined method `shorten' for #<ActionView::Base:0x1037e66a8>
Where should this method live? How can I get this to work? And what book or resource do you recommend that would make Rails seem less magical. Thank you in advance.
My experience has been: if the method is dealing with database data, best to move it to Model. Even if it is about processing data from database data, it is recommended to move it into Model if possible, to have “lean controller” and “lean view” if possible.
If the method is for generally helping to display something, then it belongs to the “helper”… for example, the
hmethod is a classic example of “helping the View code”. You can add such methods to the application helper file, which isapp/helpers/application_helpers.rbIf it is not dealing with view and not dealing with data from the database, then you might consider it being a method of that controller class, or even a method of the application controller if it is very central to your application and should be inherited by all controllers.