2
@video = Video.new
thumb = "video_thumbnail"
@video_thumbnail = @video.video_thumbnail  ## works fine 
@video_thumbnail = @video.thumb            ## undefined method `thumb'

How can I call the video_thumbnail method dynamically?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
vidur punj
  • 5,019
  • 4
  • 46
  • 65

2 Answers2

6

In Ruby, you can use send similar to this:

thumb = :video_thumbnail
@video_thumbnail = @video.send(thumb)

However, you should be aware of the potential security implications of this approach. If the contents of the thumb variable is in any way controllable by the user (e.g. by setting it from params), any user might have the possibility to call arbitrary methods on your video object. And given the large amount of meta-programming in Rails, you could easily have the ability to call and run arbitrary code that way. Because of that, you should make sure, that you tightly control the contents of the thumb variable.

If possible, you should user other means to call the methods, e.g. by using separate controller actions and proper routes to call them.

Holger Just
  • 52,918
  • 14
  • 115
  • 123
2

You have send() to dynamically invoke methods (and __send__ if the object may have overriden send)

http://ruby-doc.org/core-2.0/Object.html#method-i-send

Ven
  • 19,015
  • 2
  • 41
  • 61