status_length_validator.rb 782 B

123456789101112131415161718192021222324252627282930313233
  1. # frozen_string_literal: true
  2. class StatusLengthValidator < ActiveModel::Validator
  3. MAX_CHARS = 500
  4. def validate(status)
  5. return unless status.local? && !status.reblog?
  6. status.errors.add(:text, I18n.t('statuses.over_character_limit', max: MAX_CHARS)) if too_long?(status)
  7. end
  8. private
  9. def too_long?(status)
  10. countable_length(status) > MAX_CHARS
  11. end
  12. def countable_length(status)
  13. total_text(status).mb_chars.grapheme_length
  14. end
  15. def total_text(status)
  16. [status.spoiler_text, countable_text(status)].join
  17. end
  18. def countable_text(status)
  19. return '' if status.text.nil?
  20. status.text.dup.tap do |new_text|
  21. new_text.gsub!(FetchLinkCardService::URL_PATTERN, 'x' * 23)
  22. new_text.gsub!(Account::MENTION_RE, '@\2')
  23. end
  24. end
  25. end