module EasyComputedCustomFields
  module CustomValuePatch

    def self.included(base)

      base.send(:include, InstanceMethods)

      base.class_eval do
        after_save :update_dependent_fields , if: proc {|cv| cv.changed?}

        def update_dependent_fields
          self.custom_field.inverted_easy_dependent_custom_fields.preload(:custom_field).each do |dependent_field|
            dependent_field.custom_field.dependent_values(self.customized).each do |dependent_value|
              dependent_value.update_attribute(:value, dependent_value.customized.compute_token_value(dependent_value, "cf_#{self.custom_field_id}" => self.value))
            end
          end
        end

      end

    end

    module InstanceMethods

    end
  end
end
EasyExtensions::PatchManager.register_model_patch('CustomValue', 'EasyComputedCustomFields::CustomValuePatch')
