Skip to content

Instantly share code, notes, and snippets.

@hideshi
Created December 2, 2015 00:04
Show Gist options
  • Save hideshi/261ccc96c94a7ed5a11b to your computer and use it in GitHub Desktop.
Save hideshi/261ccc96c94a7ed5a11b to your computer and use it in GitHub Desktop.
[翻訳]Elixirでコマンドラインアプリケーションを書く ref: http://qiita.com/hideshi@github/items/615e4f859a2486e7ab58
defmodule EightBall.CLI do
def main(args) do
end
end
"Question must be a string, ending with a question mark."
mix escript.build
➜ eight_ball git:(master) ✗ mix escript.build
Compiled lib/eight_ball.ex
Generated eight_ball app
Generated escript eight_ball with MIX_ENV=dev
➜ eight_ball git:(master) ✗ ./eight_ball --question "Is Elixir awesome?"
Outlook good
➜ eight_ball git:(master) ✗ ./eight_ball --question "Is Elixir awesome"
Question must be a string, ending with a question mark.
eight_ball --question "Is Elixir great?"
eight_ball -q "Is Elixir great?"
defmodule EightBall.CLI do
def main(argv) do
{options, _, _} = OptionParser.parse(argv,
switches: [question: :string],
)
IO.inspect options
end
end
mix escript.build
➜ eight_ball git:(master) ✗ mix escript.build
Compiled lib/eight_ball/cli.ex
Generated eight_ball app
Generated escript eight_ball with MIX_ENV=dev
./eight_ball --question "Is Elixir great?"
➜ eight_ball git:(master) ✗ ./eight_ball -q "Is Elixir great?"
[question: "Is Elixir great?"]
defmodule EightBall.CLI do
def main(opts) do
{options, _, _} = OptionParser.parse(opts,
switches: [question: :string],
aliases: [q: :question] # makes '-q' an alias of '--question'
)
try do
IO.puts EightBall.ask(options[:question])
rescue
e in RuntimeError -> e
IO.puts e.message
end
end
end
defmodule EightBall.Mixfile do
use Mix.Project
def project do
[app: :eight_ball,
version: "0.0.1",
elixir: "~> 1.0",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
escript: [main_module: EightBall.CLI], # <- this line
deps: deps,
package: package ]
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment