Skip to content

Commit 8d12d3c

Browse files
committed
perf: ISO 8601フォーマットの文字列ソート最適化
- Time.parseを削除してISO 8601文字列の直接ソートに変更 - テスト環境の複雑な条件分岐を削除(pubDateのみ使用) - パフォーマンス向上:オブジェクト変換オーバーヘッドを排除 - メモリ効率化:不要なTimeオブジェクト生成を削除 改善効果: - 9行の不要な例外処理削除 - 文字列ソートによる高速化 - コードの可読性向上
1 parent efc8387 commit 8d12d3c

File tree

1 file changed

+10
-22
lines changed

1 file changed

+10
-22
lines changed

lib/tasks/news.rake

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ TASK_LOGGER = ActiveSupport::BroadcastLogger.new(
1414
ActiveSupport::Logger.new(STDOUT)
1515
)
1616

17-
# DojoNews (WordPress) REST APIから全投稿を取得するメソッド
17+
# DojoNews (WordPress) REST API から全投稿を取得するメソッド
18+
# https://news.coderdojo.jp/wp-json/wp/v2/posts (JSON)
1819
def fetch_dojo_news_posts(api_endpoint)
1920
items = []
2021

@@ -72,22 +73,13 @@ namespace :news do
7273

7374
# 2. 環境に応じたデータソースから取得
7475
if Rails.env.test? || Rails.env.staging?
75-
# テスト環境: サンプルRSSのみ
76+
# テスト環境: サンプルRSS(RSS 2.0、pubDateのみ)
7677
TASK_LOGGER.info("🧪 テスト環境: サンプルRSSから取得")
77-
feed = RSS::Parser.parse(TEST_NEWS_FEED, false)
78-
items = feed.items.map { |item|
79-
published_at = if item.respond_to?(:pubDate) && item.pubDate
80-
item.pubDate
81-
elsif item.respond_to?(:dc_date) && item.dc_date
82-
item.dc_date
83-
else
84-
raise "Unexpected RSS format: neither pubDate nor dc:date found for item: #{item.link}"
85-
end
86-
78+
items = RSS::Parser.parse(TEST_NEWS_FEED, false).items.map { |item|
8779
{
8880
'url' => item.link,
8981
'title' => item.title,
90-
'published_at' => published_at.in_time_zone('Asia/Tokyo').iso8601
82+
'published_at' => item.pubDate.in_time_zone('Asia/Tokyo').iso8601
9183
}
9284
}
9385
else
@@ -101,16 +93,12 @@ namespace :news do
10193
items = dojo_news_items + prtimes_items
10294
end
10395

104-
# 3. 古い順でソートしてID付与(1から開始)
105-
sorted_items = items.sort_by { |item| Time.parse(item['published_at']) }
106-
sorted_items.each.with_index(1) do |item, index|
107-
item['id'] = index
108-
end
109-
110-
# 4. 最新順にソート
111-
final_items = sorted_items.sort_by { |item| Time.parse(item['published_at']) }.reverse
96+
# 3. 古い順にソートして ID を付与(ISO 8601 なら文字列のままソート可能)
97+
sorted_items = items.sort_by { |item| item['published_at'] }
98+
sorted_items.each.with_index(1) { |item, index| item['id'] = index }
11299

113-
# 5. YAML ファイルに書き出し
100+
# 4. 最新順にソートして YAML ファイルに書き出す
101+
final_items = sorted_items.sort_by { |item| item['published_at'] }.reverse
114102
File.open(NEWS_YAML_PATH, 'w') do |f|
115103
formatted_items = final_items.map do |item|
116104
{

0 commit comments

Comments
 (0)