简体   繁体   中英

How to create a Mix Task to generate files

How would I create a custom mix task to dynamically generate code and files similar to how Phoenix does. For example Phoenix has generators like mix phx.gen.html that will dynamically add a bunch of files under lib. I'm not trying to accomplish anything that complicated just trying to figure out how to dynamically generate code. For example how would I create a mix task to generate file called user.ex with this code.

defmodule User do

 def function1(arg), do: arg
 def function2(arg), do: arg

end

foo = your_app_name

foo/lib/foo/mix/tasks/create_file.ex:

defmodule Mix.Tasks.CreateFile do
  use Mix.Task

  def run([file_name]) do
    app_dir = File.cwd!
    app_name = Path.basename(app_dir)
    new_file_path = Path.join(
        [app_dir, "lib", app_name, "#{file_name}.ex"]
    )

    File.write(
      new_file_path, 
      """
      defmodule #{String.capitalize(app_name)}.#{String.capitalize(file_name)} do
        def hello do
        end

        def goodbye do
        end
      end
      """, 
      [:write]
    )
  end

end

If you run the mix task:

~/phoenix_apps/foo$ mix create_file skeleton

["skeleton"] will be passed as an arg to run() , and the task will create the file:

foo/lib/foo/skeleton.ex

with the contents:

defmodule Foo.Skeleton do
  def hello do
  end

  def goodbye do
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM