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

71 lines
2.2 KiB

  1. require 'mini_magick'
  2. class Post < ApplicationRecord
  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
  6. has_many :tags, through: :post_tags
  7. has_many :user_post_views, dependent: :destroy
  8. has_many :post_similarities_as_post,
  9. class_name: 'PostSimilarity',
  10. foreign_key: :post_id
  11. has_many :post_similarities_as_target_post,
  12. class_name: 'PostSimilarity',
  13. foreign_key: :target_post_id
  14. has_one_attached :thumbnail
  15. validate :validate_original_created_range
  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_with_cos =
  26. post_similarities_as_post.select(:target_post_id, :cos)
  27. .map { |ps| [ps.target_post_id, ps.cos] } +
  28. post_similarities_as_target_post.select(:post_id, :cos)
  29. .map { |ps| [ps.post_id, ps.cos] }
  30. sorted = ids_with_cos.sort_by { |_, cos| -cos }
  31. ids = sorted.map(&:first)
  32. ids = ids.first(limit) if limit
  33. Post.where(id: ids).index_by(&:id).values_at(*ids)
  34. end
  35. def resized_thumbnail!
  36. return unless thumbnail.attached?
  37. image = MiniMagick::Image.read(thumbnail.download)
  38. image.resize '180x180'
  39. thumbnail.purge
  40. thumbnail.attach(io: File.open(image.path),
  41. filename: 'resized_thumbnail.jpg',
  42. content_type: 'image/jpeg')
  43. end
  44. private
  45. def validate_original_created_range
  46. f = original_created_from
  47. b = original_created_before
  48. return if f.blank? || b.blank?
  49. f = Time.zone.parse(f) if String === f
  50. b = Time.zone.parse(b) if String === b
  51. return if !(f) || !(b)
  52. if f >= b
  53. errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
  54. end
  55. end
  56. end