gpt4 book ai didi

ruby-on-rails - 用于布局的 Ruby Controller

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:36 26 4
gpt4 key购买 nike

我正在为我的博客开发一个 ip_to_geo 函数。我在布局中附加了一个功能。我的 /app/views/layouts/application.html.erb 看起来像这样:

<header>
<span>the geo_span I used to show ip_to_geo result</span>
</header>

<%= yield :articles %>

<footer>
</footer>

在我的 articles_controller.rb 中,我有这样的代码:

def index
ip_to_geo_in_controller
end

每次页面更新时,我都会将 geo_string 放入 welcome.coffee 中。

$(document).on "page:change", ->
update_geo_span()

我有很多共享相同布局的文章列表,每次更改列表时, Controller 中的 ip_to_geo_in_controller 都会运行。

我希望有一些方法可以让 ip_to_geo_in_controller 在我的布局加载时只运行一次。

我尝试创建 app/controllers/layouts_controller.rb,并将以下代码放入其中。但是当布局(/app/views/layouts/application.html.erb)被加载时,这个 Controller 并没有被加载。

def application
ip_to_geo_in_controller
end

最佳答案

如果我正确地理解了您想要实现的目标,缓存可能会对您有所帮助:

def index
@cached_ip ||= ip_to_geo_in_controller
end

通过这种方式计算值并将其存储在 @cached_ip 实例变量中,除非它已被缓存。

关于ruby-on-rails - 用于布局的 Ruby Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34391177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com