【发布时间】:2020-05-24 11:33:20
【问题描述】:
我想知道是否可以将 if 条件语句作为字符串或符号作为参数传递。因为方法名称或 if 语句名称可能会改变,如果我需要它来重构事物,最好使用变量, 这里是一个简单更新方法中的示例。
#within any controller
class FooController < ApplicationController
include RedirectAfterFooUpdate
# other methods
def update
@foo.update(place_params)
if @foo.save
action_after_update_foo(some_parameters)
else
# error redirection...
end
end
end
#within a module need to set correct action after update foo
module RedirectAfterFooUpdate
def action_after_update_foo(some_parameters)
if condiction_1
do_something(condiction_1.to_s.to_sym) #do_something(:condiction_1)
elsif condiction_2
do_something_else(condiction_2.to_s.to_sym) #do_something_else(:condiction_2)
elsif condiction_3
do_something_else_again(condiction_3.to_s.to_sym) #do_something_else_again(:condiction_3)
else
#casual code
end
end
end
上面的代码明显简化了,实际上我还有很多其他参数,但真正关注的是“if 语句”=> condiction_1 或 condiction_2 或 condiction_3。我们怎么会得到它的名字。
在这种情况下,问题Get the name of the currently executing method 并没有真正的帮助,因为我不需要根方法名称action_after_update_foo。
【问题讨论】:
-
你的问题我不清楚。在
action_after_update_foo(some_parameters)中,您想要传递在action_after_update_foo方法中只是作为符号传递给do_something方法的东西。为什么不首先将符号直接传递给do_something方法。为什么是中间action_after_update_foo方法? -
我理解你的提议,非常感谢。如果我将符号直接传递给“do_something”,例如
:the_foo_update_need_to_destroy_all_its_dates。你是绝对正确的,我可以做到这一点,并告诉我我的方法是如何运行的。但我会找到一种让它动态化的方法。如果条件是if only_refund_changed我想将该名称作为参数传递给 do_something 方法 => do_something(only_refund_changed)
标签: ruby-on-rails ruby ruby-on-rails-6 ruby-block