Convert CamelCase xml/json to ruby named attribute

2019-05-22 15:09发布

问题:

I'm using ActiveResource to consume a REST service. The xml from the service looks like:

<Person>
  <FirstName>Kevin</FirstName>
  <LastName>Berridge</LastName>
</Person>

ActiveResource parses this just fine, but it uses the names verbatim. So the model class will look like:

p = Person.find(1)
p.FirstName
p.LastName

I would much prefer if this would follow the Ruby naming conventions and look like:

p = Person.find(1)
p.first_name
p.last_name

Does ActiveResource have a way to do this? Is there a way I can hook into ActiveResource and add this?

回答1:

I don't know of a quick way to change the way ActiveResource names attributes, but you can implement method_missing to access the existing attributes with your preferred spellings:

def method_missing(name, *args, &block)
  send name.to_s.classify.to_sym, *args, &block
end

Alternatively, you might be able to define alternately-named methods dynamically by iterating through attributes.keys and using define_method, though I'm not sure when in your object's life cycle you would do that (constructor?).