feat: URL 正規化(#208) (#226)

#208

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #226
This commit was merged in pull request #226.
This commit is contained in:
2026-01-20 12:39:33 +09:00
parent 16ecbd1fc9
commit 86209dcc84
6 changed files with 83 additions and 6 deletions
+34
View File
@@ -17,7 +17,12 @@ class Post < ApplicationRecord
foreign_key: :target_post_id
has_one_attached :thumbnail
before_validation :normalise_url
validates :url, presence: true, uniqueness: true
validate :validate_original_created_range
validate :url_must_be_http_url
def as_json options = { }
super(options).merge({ thumbnail: thumbnail.attached? ?
@@ -69,4 +74,33 @@ class Post < ApplicationRecord
errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
end
end
def url_must_be_http_url
begin
u = URI.parse(url)
rescue URI::InvalidURIError
errors.add(:url, 'URL が不正です.')
return
end
if !(u in URI::HTTP) || u.host.blank?
errors.add(:url, 'URL が不正です.')
return
end
end
def normalise_url
return if url.blank?
self.url = url.strip
u = URI.parse(url)
return unless u in URI::HTTP
u.host = u.host.downcase if u.host
u.path = u.path.sub(/\/\Z/, '') if u.path.present?
self.url = u.to_s
rescue URI::InvalidURIError
;
end
end