続・経産省ニュースリリースをSlackに投げる

it-lawyer.hatenablog.com

昨日の続き。
他にも使い回せるようにするとこんな感じですかね。

./lib/hoge.rb

require './config/active_record'
require './config/slack'

def post_feed_to_slack(table, title_link, title, slack_username)
  hash = {
    uri: title_link,
    title: title
  }

  unless table.where(uri: hash[:uri]).reload.exists?
    Slack.chat_postMessage(
      channel: %(rss),
      username: slack_username,
      text: %(<#{hash[:uri]}|#{hash[:title]}>),
      unfurl_links: 'true'
    )

    table.create(
      uri: %(#{hash[:uri]})
    )
  end
end

def delete_unnecessary_data(table, count)
  if table.all.reload.size > count
    min_id = table.where(id: table.minimum(:id)).map(&:id)[0]
    max_id = table.where(id: table.maximum(:id)).map(&:id)[0]
    table.where(id: min_id..max_id-count).delete_all
  end
end

./meti.rb

require 'faraday'
require 'nokogiri'
require './lib/hoge'

uri = %(https://www.meti.go.jp/press/index.html)

Nokogiri::HTML(Faraday.get(uri).body).xpath('//a[@class="cut_txt"]').reverse_each do |node|
  post_feed_to_slack(
    Meti,
    %(https://www.meti.go.jp#{node[:href]}),
    node.text,
    %(経済産業省ニュースリリース)
  )
end

delete_unnecessary_data(Meti, 20)