ぼざクリタグ広場 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.
 
 
 
 
 
 

100 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.order(cos: :desc)
  26. ids = ids.limit(limit) if limit
  27. ids = ids.pluck(:target_post_id)
  28. return Post.none if ids.empty?
  29. Post.where(id: ids)
  30. .with_attached_thumbnail
  31. .order(Arel.sql("FIELD(posts.id, #{ ids.join(',') })"))
  32. end
  33. def resized_thumbnail!
  34. return unless thumbnail.attached?
  35. image = MiniMagick::Image.read(thumbnail.download)
  36. image.resize '180x180'
  37. thumbnail.purge
  38. thumbnail.attach(io: File.open(image.path),
  39. filename: 'resized_thumbnail.jpg',
  40. content_type: 'image/jpeg')
  41. end
  42. private
  43. def validate_original_created_range
  44. f = original_created_from
  45. b = original_created_before
  46. return if f.blank? || b.blank?
  47. f = Time.zone.parse(f) if String === f
  48. b = Time.zone.parse(b) if String === b
  49. return if !(f) || !(b)
  50. if f >= b
  51. errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
  52. end
  53. end
  54. def url_must_be_http_url
  55. begin
  56. u = URI.parse(url)
  57. rescue URI::InvalidURIError
  58. errors.add(:url, 'URL が不正です.')
  59. return
  60. end
  61. if !(u in URI::HTTP) || u.host.blank?
  62. errors.add(:url, 'URL が不正です.')
  63. return
  64. end
  65. end
  66. def normalise_url
  67. return if url.blank?
  68. self.url = url.strip
  69. u = URI.parse(url)
  70. return unless u in URI::HTTP
  71. u.host = u.host.downcase if u.host
  72. u.path = u.path.sub(/\/\Z/, '') if u.path.present?
  73. self.url = u.to_s
  74. rescue URI::InvalidURIError
  75. ;
  76. end
  77. end