<commit_before>class Picture < ApplicationRecord
  include OrderQuery

  belongs_to :user

  mount_uploader :image, ImageUploader

  acts_as_votable

  order_query :order_by_view, [:views_count, :desc]
  order_query :order_by_time, [:created_at, :desc]

  before_create do
    self.token = self.class.generate_unique_secure_token(:token)
  end

  def to_param
    self.token
  end

  def regenerate_token
    old_path = Rails.root.join('public', self.image.store_dir)
    self.update(token: self.class.generate_unique_secure_token(:token))
    new_path = Rails.root.join('public', self.image.store_dir)
    FileUtils.mv(old_path, new_path)
  end

  def size(version = nil)
    (version ? self.image.versions[version] : self.image).size
  end

  def charge_user(version = nil)
    self.user.decrement!(:balance, self.size(version))<commit_msg>Prevent users from uploading a picture when data balance is negative<commit_after>class Picture < ApplicationRecord
  include OrderQuery

  belongs_to :user

  mount_uploader :image, ImageUploader

  acts_as_votable

  order_query :order_by_view, [:views_count, :desc]
  order_query :order_by_time, [:created_at, :desc]

  validate :user_balance_cannot_be_negative, on: :create

  def user_balance_cannot_be_negative
    unless self.user.balance > 0
      errors.add(:user_id, 'data balance cannot be negative')
    end
  end

  before_create do
    self.token = self.class.generate_unique_secure_token(:token)
  end

  def to_param
    self.token
  end

  def regenerate_token
    old_path = Rails.root.join('public', self.image.store_dir)
    self.update(token: self.class.generate_unique_secure_token(:token))
    new_path = Rails.root.join('public', self.image.store_dir)
    FileUtils.mv(old_path, new_path)
  end

  def size(version = nil)
    (version ? self.image.versions[version] : self.image).size
  end

  def charge_user(version = nil)
    self.user.decrement!(:balance, self.size(version))
{'fraction_non_alphanumeric': 0.09768637532133675, 'fraction_numerical': 0.0005141388174807198, 'mean_word_length': 4.375690607734807, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 4, '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': '313828', 'n_tokens_mistral': 667, 'n_tokens_neox': 640, 'n_words': 133}