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

102 lines
2.7 KiB

  1. class Post < ApplicationRecord
  2. require 'mini_magick'
  3. belongs_to :uploaded_user, class_name: 'User', optional: true
  4. has_many :post_tags, dependent: :destroy, inverse_of: :post
  5. has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
  6. has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
  7. has_many :tags, through: :active_post_tags
  8. has_many :user_post_views, dependent: :delete_all
  9. has_many :post_similarities, dependent: :delete_all
  10. has_many :post_versions
  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 snapshot_tag_names = tags.joins(:tag_name).order('tag_names.name').pluck('tag_names.name')
  25. def related limit: nil
  26. ids = post_similarities.order(cos: :desc)
  27. ids = ids.limit(limit) if limit
  28. ids = ids.pluck(:target_post_id)
  29. return Post.none if ids.empty?
  30. Post.where(id: ids)
  31. .with_attached_thumbnail
  32. .order(Arel.sql("FIELD(posts.id, #{ ids.join(',') })"))
  33. end
  34. def resized_thumbnail!
  35. return unless thumbnail.attached?
  36. image = MiniMagick::Image.read(thumbnail.download)
  37. image.resize '180x180'
  38. thumbnail.purge
  39. thumbnail.attach(io: File.open(image.path),
  40. filename: 'resized_thumbnail.jpg',
  41. content_type: 'image/jpeg')
  42. end
  43. private
  44. def validate_original_created_range
  45. f = original_created_from
  46. b = original_created_before
  47. return if f.blank? || b.blank?
  48. f = Time.zone.parse(f) if String === f
  49. b = Time.zone.parse(b) if String === b
  50. return if !(f) || !(b)
  51. if f >= b
  52. errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
  53. end
  54. end
  55. def url_must_be_http_url
  56. begin
  57. u = URI.parse(url)
  58. rescue URI::InvalidURIError
  59. errors.add(:url, 'URL が不正です.')
  60. return
  61. end
  62. if !(u in URI::HTTP) || u.host.blank?
  63. errors.add(:url, 'URL が不正です.')
  64. return
  65. end
  66. end
  67. def normalise_url
  68. return if url.blank?
  69. self.url = url.strip
  70. u = URI.parse(url)
  71. return unless u in URI::HTTP
  72. u.host = u.host.downcase if u.host
  73. u.path = u.path.sub(/\/\Z/, '') if u.path.present?
  74. self.url = u.to_s
  75. rescue URI::InvalidURIError
  76. ;
  77. end
  78. end