Reputation: 2523
In my rails app I am using carrierwave for images. Carrierwave creates different versions of an image and the url can be obtained like this: picture.large.url
, picture.small.url
, picture.thumb.url
, etc.
I would like to create a method that can accept a string argument that can then be used for the image url. Something like this:
def profile_url (version)
picture.version.url
end
So then I can write @user.profile_url('thumb')
and it should give me the url in thumb size.
I get an undefined method 'version' error. Is this possible?
Upvotes: 1
Views: 106
Reputation: 114138
According to the documentation for CarrierWave's url
, you can pass the version as an argument:
When given a version name as a parameter, will return the url for that version [...]
my_uploader.url #=> /path/to/my/uploader.gif my_uploader.url(:thumb) #=> /path/to/my/thumb_uploader.gif
Your code can be written as:
class User < ActiveRecord::Base
mount_uploader :picture, PictureUploader
def profile_url(version)
picture.url(version)
end
end
And called via:
@user.profile_url('thumb')
# or
@user.profile_url(:thumb)
You could also invoke the method directly:
@user.picture.url('thumb')
# or
@user.picture.url(:thumb)
Upvotes: 1
Reputation: 211540
Normally you can do it this way:
def profile_url(version)
version = version.to_sym
case version
when :large, :small, :thumb
picture.send(version).url
end
end
The reason for the to_sym
call here is so you can call this profile_url('thumb')
or profile_url(:thumb)
and both will work.
Upvotes: 6