Reputation: 331
I was wondering if it was possible to pass as parameter the if condition statement as string or symbol. Because method name or if statement name could change and if I need it to refacto things it's better to work with a variable, here an example inside a simple update method.
#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
the code above is clearly simplified and i actually have many other paramaters, but the thing is really focus on the "if statement" => condiction_1 or condiction_2 or condiction_3. How could we get the name of it .
The question Get the name of the currently executing method is not really helpful in that case because I do not need the root method name action_after_update_foo
.
Upvotes: 1
Views: 155
Reputation: 341
If the conditions are just method invocations, you could use the following approach that uses Ruby's send
method to evaluate each condition:
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
Upvotes: 1