Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access current host and port on a model in Rails?

I am facing the following problem:

I am doing a Rails 4 webapp and we are using paperclip for profile images. If the user does not upload an image we provide a default one (like the facebook silhouette placeholder). So as paperclip eases handling default images, we are doing the following in the Profile model:

class Profile < ActiveRecord::Base
  belongs_to :user
  has_attached_file :image, :styles => { :medium => "300x300", :thumb => "100x100" }, :default_url => "assets/profiles/:style/placeholder.gif"
end

The big problem is that I need the complete URL of the image and NOT only the path so I am struggling to get the host and port before that path. Using action view helpers there did not help (asset_url helper)

I was thinking in initializing some constant or configuration or environment variable per environment. Will it be correct? Any other suggestions?

EDIT: I forgot to mention this: The resource (Profile) may have a custom picture or a default one. When it has a custom image, we store it in Amazon S3 and in that case profile.image.url returns full URL. In the other case, when it has not a custom picture it has a default image stored in app/assets/images and in that case profile.image.url returns just the path. I would like that the method image.url consistently return full URLs. – flyer88 just now edit

like image 576
flyer88 Avatar asked Oct 20 '22 19:10

flyer88


1 Answers

If, as you mention in your comment, you are providing an API endpoint, it might make more sense to determine the host, port, etc. in the controller. Something like this:

# routes.rb
get "/profile/:id" => "api#profile"

# profile.rb
def image_url_or_default request
  if image
    "#{request.protocol}#{request.host_with_port}#{image.url}"
  else
    "http://s3.amazon.com/my_bucket/default.jpg"
  end
end

# api_controller.rb
def profile
  profile = Profile.find params[:id]
  render text:profile.image_url_or_default(request)
end

profile.image.url will be the full URL of the image.

like image 104
Troy Avatar answered Oct 23 '22 14:10

Troy