使用 ActiveResource 将 CamelCase xml/json 转换为 ruby​​ 命名的属性 [英] Convert CamelCase xml/json to ruby named attributes with ActiveResource

查看:67
本文介绍了使用 ActiveResource 将 CamelCase xml/json 转换为 ruby​​ 命名的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ActiveResource 来使用 REST 服务.来自服务的 xml 看起来像:

I'm using ActiveResource to consume a REST service. The xml from the service looks like:

<Person>
  <FirstName>Kevin</FirstName>
  <LastName>Berridge</LastName>
</Person>

ActiveResource 解析得很好,但它逐字使用名称.所以模型类看起来像:

ActiveResource parses this just fine, but it uses the names verbatim. So the model class will look like:

p = Person.find(1)
p.FirstName
p.LastName

我更喜欢这是否遵循 Ruby 命名约定并如下所示:

I would much prefer if this would follow the Ruby naming conventions and look like:

p = Person.find(1)
p.first_name
p.last_name

ActiveResource 有办法做到这一点吗?有没有办法可以挂钩 ActiveResource 并添加它?

Does ActiveResource have a way to do this? Is there a way I can hook into ActiveResource and add this?

推荐答案

我不知道有什么快速的方法可以改变 ActiveResource 命名属性的方式,但是你可以实现 method_missing 来访问现有的具有您首选拼写的属性:

I don't know of a quick way to change the way ActiveResource names attributes, but you can implement method_missing to access the existing attributes with your preferred spellings:

def method_missing(name, *args, &block)
  send name.to_s.classify.to_sym, *args, &block
end

或者,您可以通过迭代 attributes.keys 并使用 define_method 来动态定义交替命名的方法,尽管我不确定 何时 在对象的生命周期中,您会这样做(构造函数?).

Alternatively, you might be able to define alternately-named methods dynamically by iterating through attributes.keys and using define_method, though I'm not sure when in your object's life cycle you would do that (constructor?).

这篇关于使用 ActiveResource 将 CamelCase xml/json 转换为 ruby​​ 命名的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆