lostisland / sawyer

Secret User Agent of HTTP
MIT License
247 stars 75 forks source link

How do I keep certain fields from a Sawyer::Resource? #28

Closed ghost closed 10 years ago

ghost commented 10 years ago

Given I have this:

forks = Octokit.forks('rafalchmiel/friction').first
forks.class # => Sawyer::Resource

How would I keep certain fields (from an Array such as [:id, :full_name]) and delete others from the forks variable? So all I want to be left with, is a Sawyer::Resource with only the :id and :full_name fields.

Adding a small method like delete to the Sawyer::Resource class would be helpful:

def delete(key)
  @_fields.delete key
  @attrs.delete key
end
pengwynn commented 10 years ago

Resource#to_hash is your friend here:

In Rails (or wherever else ActiveSupport is sold) you can use Hash#slice.

irb(main)> Octokit.forks('rafalchmiel/friction').first.to_hash.slice(:id, :full_name)
=> {:id=>18761355, :name=>"modsognir/friction"}

Otherwise, you'll need to use select:

irb(main)> Octokit.forks('rafalchmiel/friction').first.to_hash.select {|k,v| [:id, :full_name].include?(k) }
=> {:id=>18761355, :name=>"modsognir/friction"}
ghost commented 10 years ago

Awesome, thanks a lot :+1:!