LoginSignup
1
1

More than 5 years have passed since last update.

Thor を使って簡単に「テンプレート」機能を実装する

Last updated at Posted at 2017-01-19

これはなに?

複数プロジェクトが共通して利用するリポジトリがあるとします。
新規プロジェクトが参加するたびに、だれかが手動でプロジェクトディレクトリを作成して雛形から簡単なファイルを generate する作業が発生する場合があります。

ここでは、そういった作業を Thor を利用してコマンド一つですぐに「新規プロジェクト」の雛形を作成できる機能を実装してみたいと思います。(もちろんプロジェクトではなく、「新しい概念の参加」であれば基本なんにでも使えると思います。)

(想定、オーケストラレーションツールなど)

Gemfile に thor を追加

gem 'thor' を追加し、 bundle install してください。

Thorfile を作成

例を gist にしました。
- https://gist.github.com/kozyty/51d292d7e577bd055290e46c2be17301

app.tt
<%= name %>
<%= config[:username] %>
<%= config[:domain] %>
require 'thor'

class Generator < Thor::Group
  include Thor::Actions

  argument :name

  class_option :username, aliases: '-u', required: true
  class_option :domain, aliases: '-d'

  def self.source_root
    File.dirname(__FILE__)
  end

  def create_lib_file
    say "project_name: #{name}", :green
    say "username: #{options[:username]}", :green

    if options[:domain]
      say "domain: #{options[:domain]}", :green
    else
      say "Please set up domain later.", :red
    end

    config = {
      username: options[:username],
      domain: options[:domain]
    }

    template('templates/projects/app.tt', "projects/#{name}/app.rb.sample", config)
  end
end

実行方法

$ bundle exec thor generator [name] [-u username] [-d domain]

無事、雛形の .sample ファイルが生成されれば完了です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1