Madogiwa Blog

主に技術系の学習メモに使っていきます。

OK Computerのヘルスチェックをブラウザで見やすくするGemを作りました💎

OK Computerのヘルスチェックをブラウザで見やすくするGemを作ったので、使い方とかをメモしておきます📝

作ったGem

github.com

モチベーション

github.com

OK Computerはヘルスチェックをしてくれる便利なGemなのですが、Viewがテキスト or JSONのみの用意となっており、ブラウザで確認したときの表示が以下のようにちょっと成功しているか等がパット見でわかりにくかったので、

f:id:madogiwa0124:20210626155506p:plain

HTML用のViewを作成して以下のような形で見やすくしたかったのがモチベーションです👩‍🎨

f:id:madogiwa0124:20210626155533p:plain

f:id:madogiwa0124:20210626163741p:plain

使い方

GitHubリポジトリを指定してbundle installをして、

git_source(:github) { |repo| "https://github.com/#{repo}.git" }

gem 'okcomputer_html_view', github: 'Madogiwa0124/okcomputer_html_view'

以下のようにconfig/application.rbload OkcomputerHtmlView.load_pathを実行するだけです。

module YourApplication
  class Application < Rails::Application
    config.to_prepare do
      load OkcomputerHtmlView.load_path
    end
  end
end

OK Computerをmountしたパスにアクセスすると以下のような感じで表示されるはずです!

f:id:madogiwa0124:20210626155533p:plain

仕組み

OK ComputerのViewはRails engineで作られているので、以下のRails Guideを参考に

railsguides.jp

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まわり、あまり触ったことなかったのですが意外と拡張もしやすくて良いですね✨

参考

stackoverflow.com