简体   繁体   English

使用Rails助手方法

[英]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. 我想将此方法应用于视图的<%= raw link.embed_code %>部分(在此处可用),以将宽度和高度更改为所需的值。 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> 根据Karel的建议,我将该方法放在links_helper.rb中,并在视图中使用了<%= raw (link.embed_code).resize_video %> ,但undefined method resize_video for #<String:0x492bf40>此错误undefined method resize_video for #<String:0x492bf40>

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). 我建议您将helper方法放在视图的相应助手中(即,如果视图文件属于控制器xyz,则应该有一个名为xyz_helper的助手)。 This is the rails convention. 这是rails约定。 If the helper method is used in multiple controller views, we can put it in application_helper. 如果在多个控制器视图中使用了辅助方法,则可以将其放在application_helper中。

If you are getting undefined method for embed_code, we have to pass that variable as follows 如果要获取embed_code的未定义方法,则必须按以下方式传递该变量

<%= 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

Place your helper methods in a file name video_helper.rb in helpers folder. 将您的助手方法放在helpers文件夹中的文件名video_helper.rb中。 More here . 这里更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM