Skip to content

Commit 0f45187

Browse files
committed
ニュース YAML→DB インポートタスクを追加&news.yml を初期化
- lib/tasks/import_news.rake を作成し、db/news.yml の内容を News テーブルに upsert するタスクを実装 - db/news.yml を空の配列形式()で初期化
1 parent 711eabe commit 0f45187

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

db/news.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
news: []

lib/tasks/import_news.rake

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
require 'yaml'
2+
3+
namespace :news do
4+
desc "db/news.yml を読み込んで News テーブルを upsert する"
5+
task import_from_yaml: :environment do
6+
yaml_path = Rails.root.join('db', 'news.yml')
7+
raw = YAML.load_file(yaml_path)
8+
9+
# entries を計算
10+
entries = raw['news'] || []
11+
12+
entries.each do |attrs|
13+
news = News.find_or_initialize_by(url: attrs['url'])
14+
news.assign_attributes(
15+
title: attrs['title'],
16+
published_at: attrs['published_at']
17+
)
18+
news.save!
19+
puts "[news] #{news.published_at.to_date} #{news.title}"
20+
end
21+
22+
puts "Imported #{entries.size} items."
23+
end
24+
end

0 commit comments

Comments
 (0)