<commit_before># encoding: utf-8

require 'carto/storage'

module Carto
  class Asset < ActiveRecord::Base
    belongs_to :user, class_name: Carto::User
    belongs_to :organization, class_name: Carto::Organization

    serialize :storage_info, CartoJsonSymbolizerSerializer
    validates :storage_info, carto_json_symbolizer: true

    validate :validate_storage_info

    def before_destroy
      if organization_id
        location = storage_info[:location]
        storage_type = storage_info[:type]
        identifier = storage_info[:identifier]

        Storage.instance.for(location, preferred_type: storage_type).remove(identifier)
      end

      super
    end

    private

    def validate_storage_info
      if organization_id
        if storage_info
          schema = Definition.instance.load_from_file('lib/formats/asset/storage_info.json')
          indifferent_storage_info = storage_info.with_indifferent_access

          errs = JSON::Validator::fully_validate(schema, indifferent_storage_info)
          errors.add(:storage_info, errs.join(', ')) if errs.any?
        else
          errors.add(:storage_info, 'can\'t be blank')
        end
      end
    end
  end
end<commit_msg>validation refactor<commit_after># encoding: utf-8

require 'carto/storage'

module Carto
  class Asset < ActiveRecord::Base
    belongs_to :user, class_name: Carto::User
    belongs_to :organization, class_name: Carto::Organization

    serialize :storage_info, CartoJsonSymbolizerSerializer
    validates :storage_info, carto_json_symbolizer: true
    validates :storage_info, presence: true, if: :organization
    validate :validate_storage_info, if: Proc.new { organization && storage_info }

    def before_destroy
      if organization_id
        location = storage_info[:location]
        storage_type = storage_info[:type]
        identifier = storage_info[:identifier]

        Storage.instance.for(location, preferred_type: storage_type).remove(identifier)
      end

      super
    end

    private

    def validate_storage_info
      schema = Definition.instance.load_from_file('lib/formats/asset/storage_info.json')
      indifferent_storage_info = storage_info.with_indifferent_access

      errs = JSON::Validator::fully_validate(schema, indifferent_storage_info)
      errors.add(:storage_info, errs.join(', ')) if errs.any?
    end
  end
end
{'fraction_non_alphanumeric': 0.07966101694915254, 'fraction_numerical': 0.000847457627118644, 'mean_word_length': 3.593385214007782, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4194487', 'n_tokens_mistral': 688, 'n_tokens_neox': 666, 'n_words': 141}