@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?
@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?
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.
You have send()
to dynamically invoke methods (and __send__
if the object may have overriden send
)