0

我正在使用来自第三方 API 的 JSON 数据,对该数据进行一些处理,然后将模型作为 JSON 发送到客户端。传入数据的键名不是很好。其中一些是首字母缩略词,有些似乎只是随机字符。例如:

{
  aikd: "some value"
  lrdf: 1 // I guess this is the ID
}

我正在创建一个 rails ActiveResource 模型来包装此资源,但不想通过 model.lrdf 访问这些属性,因为 lrdf 到底是什么并不明显!相反,我想要一些方法将这些属性别名为另一个命名更好的属性。这样我就可以说 model.id = 1 并自动将 lrdf 设置为 1 或将 model.id 设置为自动返回 1。此外,当我调用 model.to_json 将模型发送到客户端时,我不想我的 javascript 必须了解这些奇怪的命名约定。

我试过

alias id lrdf

但这给了我一个错误,说方法 lrdf 不存在。

另一种选择是只包装属性:

def id
  lrdf
end

这可行,但是当我调用 model.to_json 时,我再次将 lrdf 视为键。

有没有人做过这样的事情?你有什么建议吗?

4

2 回答 2

1

您是否尝试过一些 before_save 魔法?也许您可以定义 attr_accessible :ldrf,然后在您的 before_save 过滤器中,将 ldrf 分配给您的 id 字段。没试过,但我觉得应该可以。

attr_accessible :ldrf

before_save :map_attributes

protected
  def map_attributes
    {:ldrf=>:id}.each do |key, value|
      self.send("#{value}=", self.send(key))
    end
  end

让我知道!

于 2011-04-13T20:29:10.413 回答
0

您可以尝试创建基于 ActiveResource::Formats::JsonFormat 的格式化程序模块并覆盖 decode()。如果您必须更新数据,则还必须覆盖 encode() 。查看您本地的 gems/activeresource-NNN/lib/active_resource/formats/json_format.rb 以了解原始 json 格式化程序的作用。

如果您的模型名称是 Model 并且您的格式化程序是 CleanupFormatter,则只需执行 Model.format = CleanupFormatter。

module CleanupFormatter
  include ::ActiveResource::Formats::JsonFormat
  extend self
  # Set a constant for the mapping.
  # I'm pretty sure these should be strings. If not, try symbols.
  MAP = [['lrdf', 'id']]

  def decode(json)
    orig_hash = super
    new_hash = {}
    MAP.each {|old_name, new_name| new_hash[new_name] = orig_hash.delete(old_name) }
    # Comment the next line if you don't want to carry over fields missing from MAP
    new_hash.merge!(orig_hash)
    new_hash
  end
end

This doesn't involve aliasing as you asked, but I think it helps to isolate the gibberish names from your model, which would never have to know those original names existed. And "to_json" will display the readable names.

于 2011-04-14T06:36:20.143 回答