简体   繁体   English

将值注入 Ruby on Rails 中的所有 link_to 方法调用

[英]Injecting values into all link_to method calls in Ruby on Rails

I have a strange requirement that I need to inject a value at the beginning of all local links.我有一个奇怪的要求,我需要在所有本地链接的开头注入一个值。 This is a legacy app and is quite large so I'm looking to do it under the hood, maybe with a monkey patch.这是一个遗留应用程序并且非常大,所以我希望在引擎盖下进行,也许使用猴子补丁。

Basically if I have a link_to "Go to dashboard", dashboard_path or link_to "Create a new Job", new_job_path that they would both generate links that look like "/some_value/dashboard" and "/some_value/jobs/new"基本上,如果我有一个link_to "Go to dashboard", dashboard_pathlink_to "Create a new Job", new_job_path ,它们都会生成看起来像“/some_value/dashboard”和“/some_value/jobs/new”的链接

Tried a few things and they all have failed.尝试了几件事,但都失败了。 Any ideas?有任何想法吗?

You can try something like this in your helper instead of monkey patching link_to.你可以在你的助手中尝试这样的事情,而不是猴子修补 link_to。

 def custom_link_to(link, url, opts={})
    url = "append_here/"+url
    link_to(link, url, opts)
  end

Now you can call this action instead of calling link_to wherever applicable and also use link_to in case if you don't want to override.现在您可以调用此操作,而不是在适用的情况下调用 link_to,如果您不想覆盖,也可以使用 link_to。

custom_link_to("Go to Dashboard",dashboard_path,{})

UPDATE更新

In case of overriding everything, something similar to this might be helpful - Monkey patching Rails如果要覆盖所有内容,类似于此的内容可能会有所帮助 - Monkey patching Rails

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

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