gpt4 book ai didi

ruby-on-rails - ruby 中的动态配置文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:05 25 4
gpt4 key购买 nike

在我的 ruby​​ 代码中,我尝试将所有输出消息放在一个文件中用于翻译目的,以防客户端想要更改返回消息,它将被组织在一个文件中。

假设我在根目录下有一个名为 messages.rb 的配置文件,我将它包含在我的 main.rb ruby​​ 进程中,例如:

需要“#{ROOT_PATH}/config/messages.rb”

该文件将包含如下内容:

class Messages  
MSG = {
:msg1 => "Account successfully created",
:msg2 => "Hello"
}
end

现在,当我调用 msg1 时,让我们在 main.rb 中说我会做类似的事情:

puts Messages::MSG[:msg2]

但如您所见,以这种方式使用它并不方便,在大多数情况下,我需要包含一些数据,例如

puts Messages::MSG[:msg2] + @username

我确信有某种动态 conf 文件或其他方法可以正确执行此操作,如果您能为我提供最佳方法和最佳性能,我将不胜感激。

谢谢

最佳答案

拥有 Proc 对象而不只是一个 String 怎么样?

module Messages  
MSG = {
msg1: ->{"Account successfully created."},
msg2: ->name{"Hello, #{name}. How are you doing?"}
msg3: ->name, age{"Hello, #{name}. You are #{age} now, congrats"}
}
end

然后你可以这样调用它

puts Messages::MSG[:msg1].call()  
puts Messages::MSG[:msg2].call(@username)
puts Messages::MSG[:msg3].call(@username, @userage)

或者,如果您希望所有消息都采用相同的参数,那么只需使用空洞的量化变量即可:

module Messages  
MSG = {
msg1: ->name, age{"Account successfully created."},
msg2: ->name, age{"Hello, #{name}. How are you doing?"}
msg3: ->name, age{"Hello, #{name}. You are #{age} now, congrats"}
}
end

然后你可以这样调用它

puts Messages::MSG[:msg1].call(@username, @userage)
puts Messages::MSG[:msg2].call(@username, @userage)
puts Messages::MSG[:msg3].call(@username, @userage)

关于ruby-on-rails - ruby 中的动态配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9424653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com