【问题标题】:Get the name of the currently if condition declaration获取当前 if 条件声明的名称
【发布时间】: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


【解决方案1】:

如果条件只是方法调用,您可以使用以下方法,使用 Ruby 的 send 方法来评估每个条件:

module RedirectAfterFooUpdate
  def action_after_update_foo(some_parameters)
    # Declare the conditions that represents method invocations
    conditions = [
      :only_refund_changed,
      :another_condition_x,
      :another_condition_y
    ]
    conditition_executed = false

    conditions.each do |condition|
      # Executes each if / elsif block
      if !conditition_executed && send(condition)
        # Invoke do_something with the condition as a symbol
        do_something(condition)

        conditition_executed = true
      end
    end

    # Executes the else block
    if !conditition_executed
      #casual code
    end
  end
end

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2020-07-24
    • 2017-06-02
    • 2012-10-30
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多