Top Level Namespace

Defined in:

Macro Summary

Macro Detail

macro define_file_overload(type, *calls, mode = "r") #

Creates a file overload for the given methods that receive a filepath (Path | String) instead of an IO as first argument. The generated method opens the file before calling the original method. Additional arguments are forwarded to the original method.

Passed methods can include arguments to select which overload to use, otherwise all overloads with the same method name are included.

Example:

module Foo
  def self.read(io : IO, arg1 : T, arg2 : U) : V; end
  def self.read(io : IO, arg3 : T, arg4 : U) : V; end
  def self.read(io : IO, arg5 : T, arg6 : U, arg7 : W) : V; end
  def self.read_all(io : IO, arg1 : T, arg2 : U) : Array(V); end
  def self.read_info(io : IO, arg1 : T, arg2 : U) : X; end
  def self.read_info(io : IO, arg3 : T, arg4 : U) : X; end
  define_file_overload(Foo, read, read_all, read_info(io, arg3, arg4))`
  def self.write(io : IO, arg1 : T, arg2 : U) : Nil; end
  define_file_overload(Foo, write, mode: "w")`
end

Generates:

# file overloads are generated for all three read methods
def self.read(path : Path | String, arg1 : T, arg2 : U) : V
  File.open(path) { |file| read(file, arg1, arg2) }
end

def self.read(path : Path | String, arg3 : T, arg4 : U, arg5 : W) : V
  File.open(path) { |file| read(file, arg3, arg4, arg5) }
end

def self.read(path : Path | String, arg5 : T, arg6 : U, arg7 : W) : V
  File.open(path) { |file| read(file, arg5, arg6, arg7) }
end

def self.read_all(path : Path | String, arg1 : T, arg2 : U) : Array(V)
  File.open(path) { |file| read_all(file, arg1, arg2) }
end

# only one file overload is generated for read_info
def self.read_info(path : Path | String, arg3 : T, arg4 : U) : X
  File.open(path) { |file| read_info(file, arg3, arg4) }
end

def self.write(path : Path | String, arg1 : T, arg2 : U) : Nil
  File.open(path, mode: "w") { |file| write(file, arg1, arg2) }
end

NOTE Must be called with a type name (not self).


[View source]