OK Computerのヘルスチェックをブラウザで見やすくするGemを作ったので、使い方とかをメモしておきます📝
作ったGem
モチベーション
OK Computerはヘルスチェックをしてくれる便利なGemなのですが、Viewがテキスト or JSONのみの用意となっており、ブラウザで確認したときの表示が以下のようにちょっと成功しているか等がパット見でわかりにくかったので、
HTML用のViewを作成して以下のような形で見やすくしたかったのがモチベーションです👩🎨
使い方
GitHubのリポジトリを指定してbundle installをして、
git_source(:github) { |repo| "https://github.com/#{repo}.git" } gem 'okcomputer_html_view', github: 'Madogiwa0124/okcomputer_html_view'
以下のようにconfig/application.rb
でload OkcomputerHtmlView.load_path
を実行するだけです。
module YourApplication class Application < Rails::Application config.to_prepare do load OkcomputerHtmlView.load_path end end end
OK Computerをmountしたパスにアクセスすると以下のような感じで表示されるはずです!
仕組み
OK ComputerのViewはRails engineで作られているので、以下のRails Guideを参考に
Controllerをオーバーライドしてhtml用のrespoonseを定義して、
OkComputer::OkComputerController.class_eval do self.view_paths = "#{::OkcomputerHtmlView.gem_dir}/app/views/ok_computer" def respond(data, status) respond_to do |format| format.text { render plain: data, status: status, content_type: "text/plain" } format.html { render "/#{action_name}", locals: {data: data, status: status}, content_type: "text/html" } format.json { render json: data, status: status } end end end
あとはself.view_paths
で指定されたディレクトリにhtml.erbを用意してあげた感じです。
またGemのinstallパスは固定値で書いてしまうと参照できなくなってしまうため、Gem::Specification.find_by_name("okcomputer_html_view").gem_dir
を使用してinstlalパスを取得して、それをGem内のコードで使用するようにしています。
# frozen_string_literal: true require_relative "okcomputer_html_view/version" module OkcomputerHtmlView def self.load_path "#{gem_dir}/app/controllers/ok_computer/ok_computer_controller.rb" end def self.gem_dir Gem::Specification.find_by_name("okcomputer_html_view").gem_dir end end
おわりに
Rails engineまわり、あまり触ったことなかったのですが意外と拡張もしやすくて良いですね✨