2017-04-16 68 views
1

在下面的代碼中structList是一個結構體列表,其中每個key是模板中的字符串,value是替換。這個Enum.reduce和String.replace組合的正確公式是什麼?

%ParamStruct{default: "Greater London", description: "Region", 
key: "ca_cert_subj_state", label: "State/County", order: 99, required: false, 
value: "Greater London"} 
key上面的一個

所以是ca_cert_subj_state和值是Greater London

這是其中置換例等取得的字符串:

sslCmd = """ 
openssl req -x509 -new -nodes -sha256 \ 
-key {{key-file-pass}}.key \ 
-days 3650 \ 
-out {{key-file-pass}}.pem \ 
-subj ""\ 
/C={{ca_cert_subj_country}}\ 
/ST={{ca_cert_subj_state}}\ 
/L={{ca_cert_subj_location}}\ 
/O={{ca_cert_subj_organization}}\ 
/OU={{ca_cert_subj_org_unit}}\ 
/CN={{ca_cert_subj_common_name}}\ 
/emailAddress={{ca_cert_email}}\ 
""" 
Enum.reduce(structList, sslCmd, fn(x, sslCmd) -> sslCmd = String.replace(sslCmd, "{{#{x.key}}}", x.value) 
    end) 

這個代碼理應積累在sslCmd中更改字符串的結果,但顯然不起作用。我不知道它應該如何遞歸或迭代。有任何想法嗎?

回答

1

我認爲兩個不同的值之間存在混淆,這兩個值都命名爲sslCmd。另外sslCmd功能分配是多餘的。

這裏是工作的代碼示例:

defmodule ParamStruct do 
    defstruct default: nil, description: nil, key: nil, label: nil, order: nil, required: false, value: nil 
end 

structList = [ 
    %ParamStruct{default: "Greater London", description: "Region", 
    key: "ca_cert_subj_state", label: "State/County", order: 99, required: false, 
    value: "Greater London"}, 
    %ParamStruct{key: "ca_cert_subj_country", value: "United Kingdom"} 
] 

sslCmd = """ 
openssl req -x509 -new -nodes -sha256 \ 
-key {{key-file-pass}}.key \ 
-days 3650 \ 
-out {{key-file-pass}}.pem \ 
-subj ""\ 
/C={{ca_cert_subj_country}}\ 
/ST={{ca_cert_subj_state}}\ 
/L={{ca_cert_subj_location}}\ 
/O={{ca_cert_subj_organization}}\ 
/OU={{ca_cert_subj_org_unit}}\ 
/CN={{ca_cert_subj_common_name}}\ 
/emailAddress={{ca_cert_email}}\ 
""" 

sslCmd = Enum.reduce(structList, sslCmd, fn(x, acc) -> 
    String.replace(acc, "{{#{x.key}}}", x.value) end) 

注意sslCmd被重新分配到的Enum.reduce/3結果。