gpt4 book ai didi

ruby-on-rails - 是否可以在运行时加载 Rails 助手?

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:16 25 4
gpt4 key购买 nike

根据特定用户选择的“模式”,我有一个可以显着变化的 View 。

我想我会把不同的行为提取到两个不同的助手中,然后在 Controller 中有这样的代码:

class MyController < ApplicationController

case mode
when 'mode1'
helper "mode1"
when 'mode2'
helper "mode2"
else
raise "Invalid mode"
end

etc...

一旦加载了正确的帮助程序,然后在两个帮助程序中定义的类似 <%= edit_item %> 的语句将为特定“模式”加载正确的表单。

这在开发中效果很好,但在生产中,case 语句只运行一次。然后你就会被第一次加载的任何助手卡住(呃!我早该知道的。)

我已经想到了其他方法来实现我需要做的事情,但我仍然认为这种使用 Helpers 是改变 View 行为的一种非常干净的方法。

有谁知道我如何在运行时加载(或重新加载)助手?

TIA:约翰

最佳答案

我可以想到几种方法来做到这一点,但不确定是否按照您的建议加载模块。

加载不同的部分并根据状态选择加载哪个。

<% if @mode = 'mode1 %>
Mode 1:
<%= render :partial => 'mode1' %>
<% else %>
Mode 2:
<%= render :partial => 'mode2' %>
<% end %>

或者,如果您想将该逻辑保留在 View 之外(这可能是一件好事),您可以在 Controller 中放置一些内容以根据模式呈现不同的操作:

def index
@mode = params[:query]
case @mode
when 'mode1' then render :action => "mode1"
when 'mode2' then render :action => "mode2"
else raise "Invalid mode"
end
end

这似乎比将逻辑放在 View 中要好得多。

关于ruby-on-rails - 是否可以在运行时加载 Rails 助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/395237/

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