1
0

20161004120214_update_pushover_agent_options.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class UpdatePushoverAgentOptions < ActiveRecord::Migration[4.2]
  2. DEFAULT_OPTIONS = {
  3. 'message' => '{{ message | default: text }}',
  4. 'device' => '{{ device }}',
  5. 'title' => '{{ title | default: subject }}',
  6. 'url' => '{{ url }}',
  7. 'url_title' => '{{ url_title }}',
  8. 'priority' => '{{ priority }}',
  9. 'timestamp' => '{{ timestamp }}',
  10. 'sound' => '{{ sound }}',
  11. 'retry' => '{{ retry }}',
  12. 'expire' => '{{ expire }}',
  13. }
  14. def up
  15. Agents::PushoverAgent.find_each do |agent|
  16. options = agent.options
  17. DEFAULT_OPTIONS.each_pair do |key, default|
  18. current = options[key]
  19. options[key] =
  20. if current.blank?
  21. default
  22. else
  23. "#{prefix_for(key)}#{current}#{suffix_for(key)}"
  24. end
  25. end
  26. agent.save!(validate: false)
  27. end
  28. end
  29. def down
  30. Agents::PushoverAgent.transaction do
  31. Agents::PushoverAgent.find_each do |agent|
  32. options = agent.options
  33. DEFAULT_OPTIONS.each_pair do |key, default|
  34. current = options[key]
  35. options[key] =
  36. if current == default
  37. ''
  38. else
  39. current[/\A#{Regexp.quote(prefix_for(key))}(.*)#{Regexp.quote(suffix_for(key))}\z/, 1]
  40. end or raise ActiveRecord::IrreversibleMigration, "Cannot revert migration once Pushover agents are configured"
  41. end
  42. agent.save!(validate: false)
  43. end
  44. end
  45. end
  46. def prefix_for(key)
  47. "{% capture _default_ %}"
  48. end
  49. def suffix_for(key)
  50. "{% endcapture %}" << DEFAULT_OPTIONS[key].sub(/(?=\}\}\z)/, '| default: _default_ ')
  51. end
  52. end