Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - building an absolute url in a model's virtual attribute without url helper

I have a model that has paperclip attachments.

The model might be used in multiple rails apps

I need to return a full (non-relative) url to the attachment as part of a JSON API being consumed elsewhere.

I'd like to abstract the paperclip aspect and have a simple virtual attribute like this:

  def thumbnail_url
    self.photo.url(:thumb)
  end

This however only gives me the relative path. Since it's in the model I can't use the URL helper methods, right?

What would be a good approach to prepending the application root url since I don't have helper support? I would like to avoid hardcoding something or adding code to the controller method that assembles my JSON.

Thank you

like image 881
Nick Avatar asked Apr 23 '10 00:04

Nick


2 Answers

The url helper takes the host name from the incoming request. A model doesn't need a request to exist, hence why you can't use the URL helpers.

One solution is to pass the request hostname to the thumbnail url helper.

def thumbnail_url(hostname)
  self.photo.url(:thumb, :host => hostname)
end

Then call it from your controllers / views like this

photo.thumbnail_url(request.host)

It turns out that there isn't really a foolproof way to get the host name of a server. If a user adds an entry to their /etc/hosts file, they can access the server with whatever host name they want. If you rely the incoming request's hostname, it could be used to break the thumbnails.

Because of this, I generally hardcode my site's host name in an initializer. e.g. put this in config/initializers/hostname.rb

HOSTNAME = 'whatever'

-- edit --

It looke like in rails 3 you have to provide the :only_path => false parameter to get this to work. Here's an example from the console:

>> app.clients_path :host => 'google.com', :only_path => false
=> "http://google.com/clients"
like image 104
zaius Avatar answered Nov 12 '22 10:11

zaius


In Rails 3.0, the include given above results in a deprecation warning.

In Rails 3.0, use the following code instead to include url helpers:

class Photo < ActiveRecord::Base
  include Rails.application.routes.url_helpers
end
like image 2
Majiy Avatar answered Nov 12 '22 11:11

Majiy