1

我想知道是否可以将 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。我们怎么会得到它的名字。在这种情况下,获取当前执行方法的名称这个问题并没有真正的帮助,因为我不需要根方法名称action_after_update_foo

4

1 回答 1

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
于 2020-05-24T13:44:45.120 回答