How to parse a Mash from LinkedIn to create a Ruby object

不想你离开。 提交于 2019-12-10 08:23:17

问题


I used LinkedIn gem by pengwynn to get authentication from LinkedIn. Everything works fine, and I get a Mash in a callback that looks like this:

#<LinkedIn::Mash all=[#<LinkedIn::Mash company=#<LinkedIn::Mash id=1422 industry="Banking"    
 name="Company" size="10,001+ employees" ticker="ABC" type="Public Company"> id=2851554 
 is_current=true start_date=#<LinkedIn::Mash month=12 year=2008> summary="" title="Boss">] total=1>

How can I parse it to something similar to Rails params in order to create a new object from it?

Thank you.


回答1:


When you receive list of connections of any sort from LinkedIn, you need to get to the list from all. On the object you received from LinkedIn, you have {all, total}. total will give you the number of objects in the array, all will give you all of the objects. So if you wanted to turn the first company into a hash, you would call object.all.first.to_hash. You can iterate through all of them by doing object.all.each {|c| # your block}.

If your own Rails models match the objects being returned from the linkedin gem, you can do:

companies.all.each do |company|
  Company.create(company.to_hash)
end

If they don't map 1:1, you can just choose the fields you want:

companies.all.each do |company|
  c = Company.new
  c.name = company.name
  c.year_founded = company.start_date.year
  c.ticker = company.ticker
  # etc. etc. etc.
  c.save
end



回答2:


You can just call .to_hash to turn a Mash into a Hash (like params).

Source:

https://github.com/intridea/hashie/blob/master/lib/hashie/hash.rb



来源:https://stackoverflow.com/questions/8197835/how-to-parse-a-mash-from-linkedin-to-create-a-ruby-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!