Rails Paperclip and default_url

694 Views Asked by At

I've trying to use holder.js library for paperclip default images. Holder.js create data-src image preview, when an image have src="holder.js/#{width}x#{height}" But can't create correct url. Actually i have two problems:

First problem, is a get thumbnail style_name, for get style size.

Second, create image src with relative path (holder.js/100x100 - for example). rails prepends /assets/ for generated url.

1

There are 1 best solutions below

0
On

Here is my solution.

Define STYLES constant in your model.

app/models/post.rb

class Post < ActiveRecord::Base
  # ...

  STYLES = {
    large: '300x300#',
    medium: '250x250#',
    small: '100x100#',
    thumb: '50x50#',
    tiny: '20x20#'
  }

  has_attached_file :attachment, {
    styles: STYLES,
    default_url: '/assets/holder.js/:dimension',
    path: # your path
    url: # your url
  }

  # ...
end

Than create new Paperclip interpolation

config/initializers/paperclip.rb

# returns value of the STYLES[:dimansion]
# Post::STYLES[:tiny] -> '20x20'
Paperclip.interpolates :dimension do |attachment, style|
  key = style.to_sym
  return Post::STYLES[key].gsub(/[^\d\w+]/, '') if Post::STYLES.has_key?(key)
  '900x500' # or return default :original dimensions
end

And, finally, in your views:

<%= image_tag nil, { data: { src: 'holder.js/200x200' } } %>

or

<%= tag :img, { src: '', data: { src: 'holder.js/200x200' } } %>

Hope this helps.

PS. Better use holder_rails gem

UPDATE: Afraid you have to use

default_url: '/assets/holder.js/:dimension'

instead

default_url: 'holder.js/:dimension'

(got routing error)

Hope to solve this problem soon.