nanocのソースを読む
nanocのソースを読んで、使えるコマンドなどを調べてみよう。
まずは、nanocのコマンドであるnanoc3ファイルを見てみる。
以下のソースはほぼすべて抜粋です。
nanoc3
require 'nanoc3' require 'nanoc3/cli' # Run base Nanoc3::CLI::Base.shared_base.run(ARGV)
requireして、引数をshared_base.runに渡している。
Nanoc3::CLI::Base.shared_base
def self.shared_base @shared_base ||= Nanoc3::CLI::Base.new end
=を使って最初の一回だけnewするようにしている。だからshared_baseなのかな。。 |
最初のrunは、Nanoc3::CLI::Base#runのようだ。
次はrunを見てみる。
Nanoc3::CLI::Base#run
def run(args) super(args) rescue Interrupt => e exit(1) rescue StandardError, ScriptError => e print_error(e) exit(1) end
super(args)となっているので、スーパークラスを見ればよいのか。
module Nanoc3::CLI class Base < Cri::Base
Cri::Base#runを見れば良いようだ。Criはnanoc3をインストールされたときに、
一緒にインストールされたgemのようです。Criがいつrequireされてたかというと、最初のrequire 'nanoc3/cli'を
したときにnanoc3/cliの中でrequireされていた。
Cri::Base#run
def run(args) # Check arguments if args.length == 0 @help_command.run([], []) exit 1 end # もっと続く。。。
何も引数を与えずにnanoc3すると、@help_command.runが呼ばれてexitする。
@help_commandは何かというと
#Cri::Base attr_accessor :help_command
#Nanoc3::CLI::Base self.help_command = Nanoc3::CLI::Commands::Help.new
このHelpクラスのようにCommandっぽいクラスは\nanoc3\cli\commandsディレクトリの下に
autocompile.rb compile.rb create_item.rb create_layout.rb create_site.rb debug.rb help.rb info.rb update.rb view.rb
とあって、Helpクラスもhelp.rbに書いてある。nanocのヘルプを呼ぶと、これらに対応するような
commandがある。
[saliy@localhost ~]$ nanoc3 nanoc, a static site compiler written in Ruby. Available commands: autocompile start the autocompiler compile compile items of this site create_item create a item create_layout create a layout create_site create a site debug show debug information for this site help show help for a command info show info about available plugins update update the data stored by the data source to a newer version view start the web server that serves static files
なので、"nanoc3 コマンド名"を実行すると、コマンドに対応するクラスのrunが呼ばれるのかな、と想像してみる。
Nanoc3::CLI::Commands::Help#run
def run(options, arguments) # Check arguments if arguments.size > 1 $stderr.puts "usage: #{usage}" exit 1 end if arguments.length == 0 # Build help text text = '' # Add title text << "nanoc, a static site compiler written in Ruby.\n" # もっと続く。。。
puts text
いまの場合、arguments.lengthは0。
textにnanocのヘルプを詰めてputsする。そして、呼び出し元に戻るとexit 1 して終了。
nanoc3を何も引数を付けずに呼び出すと、Nanoc3::CLI::Commands::Help#runで、ヘルプが出力されることが分かった。
もうちょっと読んでみよう。