别名属性ruby ActiveResource :: Base

时间:2013-10-21 14:26:07

标签: ruby api activeresource

class ChatMessage < ActiveResource::Base
 alias_attribute :user_id, :userId
 alias_attribute :chat_id, :chatId
 alias_attribute :message_text, :MessageText
 ...

我遇到的问题是,我从API返回的内容具有我不喜欢的属性名称,例如看到camelCaps。我不想对我的应用程序中的每个模型执行此操作。是否有一些方法缺少我应用的魔法?

干杯 托马斯

1 个答案:

答案 0 :(得分:2)

你可以在这里做一些元编程:

module JavaAliasing
  def initialize(hash)
    super(Hash[hash.map do |k,v|
      [k.to_s.gsub(/[a-z][A-Z]/) { |s| s.split('').join('_') }.downcase.to_sym, v]
    end])
  end
end

让我说明一下:

class Instantiator
  def initialize(hash)
    hash.each { |k,v| instance_variable_set "@#{k}", v }
  end
end

Instantiator.new(asdf: 2).instance_variable_get('@asdf') #=> 2

class MyARModel < Instantiator
  include JavaAliasing
end

MyARModel.new(asdfQWER: 2).instance_variable_get("@asdf_qwer") #=> 2

这里是一个现实生活中的例子(rails 4.0):

> Player.send :include, JavaAliasing
> Player.new(name: 'pololo', username: 'asdf', 'teamId' => 23)
=> #<Player id: nil, name: "pololo", username: "asdf", email: nil, type: "Player", created_at: nil, updated_at: nil, provider: nil, uid: nil, team_id: 23, last_login: nil, last_activity: nil>