Search code examples
rubyapiactiveresource

Alias attribute ruby ActiveResource::Base


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

I Have the problem that what I return from an API has attribute names that I don't like, e.g. see camelCaps. I don't want to do this to every model in my application. Is there some method missing magic I could apply?

Cheers Thomas


Solution

  • You can do a little of metaprogramming here:

    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
    

    Let me illustrate this:

    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
    

    Here, a real life example (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>