set_defaults.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class ObjectManager
  3. class Attribute
  4. class SetDefaults
  5. def after_initialize(record)
  6. return if !record.new_record?
  7. attributes_for(record).each { |attr, config| set_value(record, attr, config) }
  8. end
  9. private
  10. def set_value(record, attr, config)
  11. method_name = "#{attr}="
  12. return if !record.respond_to? method_name
  13. return if record.send(:"#{attr}_came_from_user?")
  14. record.send method_name, build_value(config)
  15. end
  16. def build_value(config)
  17. method_name = "build_value_#{config[:data_type]}"
  18. return send(method_name, config) if respond_to?(method_name, true)
  19. config[:default]
  20. end
  21. def build_value_date(config)
  22. diff = config[:diff]
  23. return if !diff
  24. Time.use_zone(Setting.get('timezone_default')) do
  25. diff
  26. .days
  27. .from_now
  28. .to_date
  29. end
  30. end
  31. def build_value_datetime(config)
  32. diff = config[:diff]
  33. return if !diff
  34. Time.use_zone(Setting.get('timezone_default')) do
  35. diff
  36. .hours
  37. .from_now
  38. .change(usec: 0, sec: 0)
  39. .utc
  40. end
  41. end
  42. def attributes_for(record)
  43. query = ObjectManager::Attribute.active.editable.for_object(record.class)
  44. cache_key = "#{query.cache_key_with_version}/attribute_defaults"
  45. Rails.cache.fetch cache_key do
  46. query
  47. .map { |attr| { attr.name => config_of(attr) } }
  48. .reduce({}, :merge)
  49. .compact
  50. end
  51. end
  52. def config_of(attr)
  53. case attr.data_type
  54. when 'date', 'datetime'
  55. {
  56. data_type: attr.data_type,
  57. diff: attr.data_option&.dig(:diff)
  58. }
  59. else
  60. {
  61. data_type: attr.data_type,
  62. default: attr.data_option&.dig(:default)
  63. }
  64. end
  65. end
  66. end
  67. end
  68. end