trabajo-afectivo/app/models/object_manager/attribute/set_defaults.rb
2022-01-01 14:38:12 +01:00

67 lines
1.7 KiB
Ruby

# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
class ObjectManager
class Attribute
class SetDefaults
def after_initialize(record)
return if !record.new_record?
attributes_for(record).each { |attr, config| set_value(record, attr, config) }
end
private
def set_value(record, attr, config)
method_name = "#{attr}="
return if !record.respond_to? method_name
return if record.send("#{attr}_came_from_user?")
record.send method_name, build_value(config)
end
def build_value(config)
method_name = "build_value_#{config[:data_type]}"
return send(method_name, config) if respond_to?(method_name, true)
config[:default]
end
def build_value_date(config)
config[:diff]&.days&.from_now
end
def build_value_datetime(config)
config[:diff]&.hours&.from_now&.change(usec: 0, sec: 0)
end
def attributes_for(record)
query = ObjectManager::Attribute.active.editable.for_object(record.class)
cache_key = "#{query.cache_key_with_version}/attribute_defaults"
Rails.cache.fetch cache_key do
query
.map { |attr| { attr.name => config_of(attr) } }
.reduce({}, :merge)
.compact
end
end
def config_of(attr)
case attr.data_type
when 'date', 'datetime'
{
data_type: attr.data_type,
diff: attr.data_option&.dig(:diff)
}
else
{
data_type: attr.data_type,
default: attr.data_option&.dig(:default)
}
end
end
end
end
end