\$\begingroup\$
\$\endgroup\$
1
I have n-times similar statements
if trigger_data.tt_closed
unless trouble_ticket.changes.key?(:status)
@run = 0
break
end
unless trouble_ticket.changes[:status][1] == "Closed"
@run = 0
break
end
end
if trigger_data.tt_assignee
unless trouble_ticket.changes.key?(:assigned_to)
@run = 0
break
end
unless trouble_ticket.changes[:assigned_to][1] == trigger_data.tt_assignee
@run
break
end
end
How to refactoring that code? Maybe dynamic statement build with pass some hash to input. I'm newbie in metaprogramming. Give me advise please
asked May 26, 2012 at 21:25
-
\$\begingroup\$ Did you forget @run = 0 in the final one? \$\endgroup\$Rahul Gopinath– Rahul Gopinath2012年05月26日 22:49:55 +00:00Commented May 26, 2012 at 22:49
1 Answer 1
\$\begingroup\$
\$\endgroup\$
Are you inside a loop? Here is a possible way of doing it
def check(td, tt, trigger, key, ticket_changes)
if td.send(trigger)
unless tt.changes.key?(key)
@run = 0
return true
end
unless tt.changes[key][1] == ticket_changes
@run = 0
return true
end
end
return false
end
def metacheck(td, tt)
[[:tt_closed, :status, "Closed"],
[:tt_assignee, :assigned_to, td.tt_assignee]].each do |k|
return if check(td, tt, k[0], k[1], k[2])
end
end
metacheck(trigger_data, trouble_ticket)
I have used an array of triplets to check the conditions. The check can further be simplified as
def check(td, tt, trigger, key, ticket_changes)
return false unless td.send(trigger)
if !tt.changes.key?(key) or (tt.changes[key][1] != ticket_changes)
@run = 0
return true
end
return false
end
We can join all the conditions together. But I think this captures the original intension best.
answered May 26, 2012 at 23:14
lang-rb