ぼざクリタグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

98 lines
2.7 KiB

  1. class Post < ApplicationRecord
  2. require 'mini_magick'
  3. belongs_to :parent, class_name: 'Post', optional: true, foreign_key: 'parent_id'
  4. belongs_to :uploaded_user, class_name: 'User', optional: true
  5. has_many :post_tags, dependent: :destroy, inverse_of: :post
  6. has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
  7. has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
  8. has_many :tags, through: :active_post_tags
  9. has_many :user_post_views, dependent: :delete_all
  10. has_many :post_similarities, dependent: :delete_all
  11. has_one_attached :thumbnail
  12. before_validation :normalise_url
  13. validates :url, presence: true, uniqueness: true
  14. validate :validate_original_created_range
  15. validate :url_must_be_http_url
  16. def as_json options = { }
  17. super(options).merge({ thumbnail: thumbnail.attached? ?
  18. Rails.application.routes.url_helpers.rails_blob_url(
  19. thumbnail, only_path: false) :
  20. nil })
  21. rescue
  22. super(options).merge(thumbnail: nil)
  23. end
  24. def related(limit: nil)
  25. ids = post_similarities.select(:target_post_id).order(cos: :desc)
  26. ids = ids.limit(limit) if limit
  27. ids = ids.pluck(:target_post_id)
  28. return [] if ids.empty?
  29. Post.where(id: ids).order(Arel.sql("FIELD(id, #{ ids.join(',') })"))
  30. end
  31. def resized_thumbnail!
  32. return unless thumbnail.attached?
  33. image = MiniMagick::Image.read(thumbnail.download)
  34. image.resize '180x180'
  35. thumbnail.purge
  36. thumbnail.attach(io: File.open(image.path),
  37. filename: 'resized_thumbnail.jpg',
  38. content_type: 'image/jpeg')
  39. end
  40. private
  41. def validate_original_created_range
  42. f = original_created_from
  43. b = original_created_before
  44. return if f.blank? || b.blank?
  45. f = Time.zone.parse(f) if String === f
  46. b = Time.zone.parse(b) if String === b
  47. return if !(f) || !(b)
  48. if f >= b
  49. errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
  50. end
  51. end
  52. def url_must_be_http_url
  53. begin
  54. u = URI.parse(url)
  55. rescue URI::InvalidURIError
  56. errors.add(:url, 'URL が不正です.')
  57. return
  58. end
  59. if !(u in URI::HTTP) || u.host.blank?
  60. errors.add(:url, 'URL が不正です.')
  61. return
  62. end
  63. end
  64. def normalise_url
  65. return if url.blank?
  66. self.url = url.strip
  67. u = URI.parse(url)
  68. return unless u in URI::HTTP
  69. u.host = u.host.downcase if u.host
  70. u.path = u.path.sub(/\/\Z/, '') if u.path.present?
  71. self.url = u.to_s
  72. rescue URI::InvalidURIError
  73. ;
  74. end
  75. end