Hi all,
i have a module like this…
defmodule Fw.Code.String do
def formatBy( string, opts ) when is_list( opts ) == false, do: formatBy( string, [ opts ] )
def formatBy( string, opts \\ [] ) do
splites = String.split( string, "{" )
results =
Enum.reduce( splites, [], fn( string, results ) ->
if ( !String.contains?( string, "}" ) ) do
results ++ [ string ]
else
[ formatKey, strB ] = String.split( string, "}" )
{ indexArg, notIntPart } =
case Integer.parse( formatKey ) do
{ a, b } -> { a, b }
:error -> { 0, formatKey }
end
arg =
if ( notIntPart != "" ) do
Keyword.get( opts, String.to_atom( formatKey ), nil )
else
Enum.at( opts, indexArg )
end
results =
if ( arg != nil ) do
results ++ [ arg ]
else
results
end
results ++ [ strB ]
end
end )
Enum.join( results, "" )
end
end
and here is unit test…
test "format" do
#------------------------------------------
# case 1
#------------------------------------------
input = "123{0}456"
expect = "123456"
result = Fw.Code.String.formatBy( input )
assert( expect == result, "result[#{ inspect result }] need match[#{ expect }]" )
#------------------------------------------
# case 2
#------------------------------------------
input = "123{0}456"
expect = "123ZZ456"
result = Fw.Code.String.formatBy( input, [ "ZZ" ] )
assert( expect == result, "result[#{ inspect result }] need match[#{ expect }]" )
#------------------------------------------
# case 3
#------------------------------------------
input = "123{a}456"
expect = "123AAA456"
result = Fw.Code.String.formatBy( input, a: "AAA" )
assert( expect == result, "result[#{ inspect result }] need match[#{ expect }]" )
#------------------------------------------
# case 4
#------------------------------------------
input = "123{a}456{b}"
expect = "123AAA456BBB"
result = Fw.Code.String.formatBy( input, a: "AAA", b: "BBB" )
assert( expect == result, "result[#{ inspect result }] need match[#{ expect }]" )
#------------------------------------------
# case 5
#------------------------------------------
input = "123{0}456{1}"
expect = "123AAA456BBB"
result = Fw.Code.String.formatBy( input, [ "AAA", "BBB" ] )
assert( expect == result, "result[#{ inspect result }] need match[#{ expect }]" )
end
it’s work method,
but i always get warning message…
warning: def formatBy/2 has multiple clauses and also declares default values. In such cases, the default values should be defined in a header. Instead of:
def foo(:first_clause, b \\ :default) do ... end
def foo(:second_clause, b) do ... end
one should write:
def foo(a, b \\ :default)
def foo(:first_clause, b) do ... end
def foo(:second_clause, b) do ... end
but i can’t switch functions order,
because it’s optional argument function,
if switch order the unit test will fail,
how can i fix this warning?
thanks