Ruby:如何在哈希中为命名空间添加前缀
我所处的情况是,我需要找出哈希的级别,并为该级别中的所有元素应用命名空间。
这是这样的场景:
我有一个用我的数据填充的对象。
接下来我将对象转换为哈希。
#将对象转换为哈希 def my_hash 哈希[instance_variables.map { |var| [var[1..-1].to_sym,instance_variable_get(var)] }] 结尾
最后,我想循环遍历哈希并将不同的命名空间应用于我的嵌套哈希。
不幸的是,我无法找到一个好的解决方案来直接使用 savon gem 来执行此操作:
soap.body = request_object.my_hash
我将检查每个元素并尝试递归地找到分类方法中的嵌套级别:(这需要更多魔法)
def 分类(o) 案例o 当哈希 #需要将其重构为嵌套哈希的前缀:data NS,覆盖默认的:mes NS。 h = {} o.each {|k,v| h[k] = 分类(v)} 小时 别的 o级 结尾 结尾 soap.body = 分类(request_object.my_hash)
它应该看起来像这样,源哈希:
{:UserTicket=>'123',:ImpersonationUsername=>'dave',:TicketSettings=>{:ResourceId=>'abcd',:ClientIp=>'0',:Username=>'bobby'}}
输出(其中 mes 和 data 是两个命名空间):
{'mes:UserTicket'=>'123','mes:ImpersonationUsername'=>'dave','mes:TicketSettings'=>{'data:ResourceId'=>'abcd','data:ClientIp'=>'0','data:Username'=>'bobby'}}
I am in a situation where I need to find out the level of the hash and apply a namespace for all elements in that level.
This is the scenario:
I have an object which is populated with my data.
Next I convert the object to hash.
#convert Object to Hash def my_hash Hash[instance_variables.map { |var| [var[1..-1].to_sym, instance_variable_get(var)] }] end
Finally I would like to loop thru the hash and apply a different Namespace to my nested hash.
Unfortunately I wasn't able to find a good solution to do this with savon gem directly:
soap.body = request_object.my_hash
I will inspect each element and try to find the nested level in classify method recursively: (this requires some more magic)
def classify(o) case o when Hash #Need to refactor this to prefix :data NS for nested hash, overwriting the default :mes NS. h = {} o.each {|k,v| h[k] = classify(v)} h else o.class end end soap.body = classify(request_object.my_hash)
It should look like this, The source hash:
{:UserTicket=>'123',:ImpersonationUsername=>'dave',:TicketSettings=>{:ResourceId=>'abcd',:ClientIp=>'0',:Username=>'bobby'}}
Output (where mes and data are two Namespaces):
{'mes:UserTicket'=>'123','mes:ImpersonationUsername'=>'dave','mes:TicketSettings'=>{'data:ResourceId'=>'abcd','data:ClientIp'=>'0','data:Username'=>'bobby'}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种传递与每个嵌套级别关联的标识符列表的方法:
如果您使用递归算法,您就有机会修改您向下挖掘的每个级别所应用的范围。
Here's an approach where you pass in a list of identifiers associated with each level of nesting:
If you're using a recursive algorithm you have the opportunity to modify the scope of what's being applied with each level you dig down.