2011-04-13 66 views
0

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

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

我创建一个轨道的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的钥匙。

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

回答

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 

让我知道!

+0

我认为这可以用于保存,但在我的情况下,数据是只读的,所以我只关心在读取时转换它。 – Brad 2011-04-13 21:08:53

+0

我最终做了类似的地方,我重写了ActiveResource :: Base的加载方法。 – Brad 2011-05-23 15:57:18

0

您可以尝试创建基于ActiveResource :: Formats :: JsonFormat的格式化程序模块并覆盖decode()。如果你必须更新数据,你必须重写encode()。查看当地的gems/activeresource-N.N.N/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 

这不涉及别名,你问过,但我认为它有助于隔离模型中的乱码名字,就永远不会知道这些原始名称存在。 “to_json”将显示可读的名称。