Dru
Dru

Reputation: 9820

Using rails helper method

I've found a helper method that I would like to use to resize embedded videos on my site. I've tried using this method several ways but received multiple undefined method errors. Here's the method:

def resize_video(new_width,new_height)
    width,height = embed_code.match(/width=.?(\d+).*height=.?(\d+)/).to_a.drop(1)
    embed_code.gsub(width,new_width).gsub(height,new_height)
end

I would like to apply this method to the <%= raw link.embed_code %> portion of my view, available HERE, to change the width and height to the desired values. Where should I put the method and how should it be called?

Update

Per Karel's advice, I put the method in links_helper.rb and used <%= raw (link.embed_code).resize_video %> in the view but received this error undefined method resize_video for #<String:0x492bf40>

Upvotes: 0

Views: 2745

Answers (2)

nkm
nkm

Reputation: 5914

I would suggest you to put the helper method in the corresponding helper of the view(ie. if the view file belongs a controller xyz, there should be a helper with name xyz_helper). This is the rails convention. If the helper method is used in multiple controller views, we can put it in application_helper.

If you are getting undefined method for embed_code, we have to pass that variable as follows

<%= raw resize_video(link.embed_code, width, height) %>
def resize_video(embed_code, new_width, new_height)
  width,height = embed_code.match(/width=.?(\d+).*height=.?(\d+)/).to_a.drop(1)
  embed_code.gsub(width,new_width).gsub(height,new_height)
end

Upvotes: 1

Karel Frajt&#225;k
Karel Frajt&#225;k

Reputation: 4489

Place your helper methods in a file name video_helper.rb in helpers folder. More here.

Upvotes: 0

Related Questions