user4584963 user4584963 - 6 months ago 10
Ruby Question

How to use a method's string argument as a method name variable

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?

Answer

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.