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

我有一个问题,即我从 API 返回的内容具有我不喜欢的属性名称,例如参见 camelCaps。我不想对我的应用程序中的每个模型都这样做。有什么方法缺少我可以应用的魔法吗?

干杯托马斯

4

1 回答 1

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>
于 2013-10-21T17:02:16.690 回答