<commit_before>class AssetAssociation < Datum
  plugin MongoMapper::Plugins::Dirty

  attr_accessor :should_revert_to_asset_attributes,
                :should_clear_association

  key :title, String
  key :description, String
  key :author, String
  key :asset_id, ObjectId
  key :allowed_asset_filetypes, Array, :default => lambda { [] }
  belongs_to :asset

  before_save :notify_asset
  before_validation :clear_association
  before_validation :revert_to_asset_attributes

  def title
    self_or_asset_attribute 'title'
  end

  def description
    self_or_asset_attribute 'description'
  end

  def author
    self_or_asset_attribute 'author'
  end

  private
  
  def self_or_asset_attribute(attribute)
    if self[attribute].present?
      self[attribute]
    elsif self.asset
      asset.public_send attribute
    end
  end

  def clear_association
    if !!Boolean.to_mongo(should_clear_association) && asset_id.present?
      self.should_revert_to_asset_attributes = true
      revert_to_asset_attributes
      self['asset_id'] = nil
    end
  end

  def revert_to_asset_attributes<commit_msg>Fixed extreamly strange bug that made asset associations asset method get stuck as nil. We should follow this up.<commit_after>class AssetAssociation < Datum
  plugin MongoMapper::Plugins::Dirty

  attr_accessor :should_revert_to_asset_attributes,
                :should_clear_association

  key :title, String
  key :description, String
  key :author, String
  key :asset_id, ObjectId
  key :allowed_asset_filetypes, Array, :default => lambda { [] }
  belongs_to :asset

  before_save :notify_asset
  before_validation :clear_association
  before_validation :revert_to_asset_attributes

  def title
    @title ||= self_or_asset_attribute 'title'
  end

  def description
    @description ||= self_or_asset_attribute 'description'
  end

  def author
    @author ||= self_or_asset_attribute 'author'
  end

  private
  
  def self_or_asset_attribute(attribute)
    if self[attribute].present?
      self[attribute]
    elsif asset_id.present?
      asset[attribute] if self.asset
    end
  end

  def clear_association
    if !!Boolean.to_mongo(should_clear_association) && asset_id.present?
      self.should_revert_to_asset_attributes = true
      revert_to_asset_attributes
      self['asset_id'] = nil
    end
  end

  def revert_to_asset_attributes
{'fraction_non_alphanumeric': 0.062340966921119595, 'fraction_numerical': 0.0, 'mean_word_length': 3.976793248945148, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '4635210', 'n_tokens_mistral': 743, 'n_tokens_neox': 716, 'n_words': 169}