class Redd::Utilities::Unmarshaller
Unmarshals hashes into objects.
Constants
- MAPPING
Contains the mapping from 'kind' strings to classes. TODO: UserList type!
Public Class Methods
new(client)
click to toggle source
# File lib/redd/utilities/unmarshaller.rb, line 22 def initialize(client) @client = client end
Public Instance Methods
unmarshal(res)
click to toggle source
# File lib/redd/utilities/unmarshaller.rb, line 26 def unmarshal(res) # I'm loving the hell out of this pattern. model = js_listing(res) || js_model(res) || api_listing(res) || api_model(res) raise "cannot unmarshal: #{res.inspect}" if model.nil? model end
Private Instance Methods
api_listing(res)
click to toggle source
Unmarshal API-provided listings.
# File lib/redd/utilities/unmarshaller.rb, line 50 def api_listing(res) return nil unless res[:kind] == 'Listing' attributes = res[:data] attributes[:children].map! { |child| unmarshal(child) } Models::Listing.new(@client, attributes) end
api_model(res)
click to toggle source
Unmarshal API-provided model.
# File lib/redd/utilities/unmarshaller.rb, line 58 def api_model(res) return nil unless MAPPING[res[:kind]] MAPPING[res[:kind]].new(@client, res[:data]) end
js_listing(res)
click to toggle source
Unmarshal frontent API-style listings
# File lib/redd/utilities/unmarshaller.rb, line 36 def js_listing(res) # One day I'll get to deprecate Ruby 2.2 and jump into the world of Hash#dig. return nil unless res[:json] && res[:json][:data] && res[:json][:data][:things] Models::Listing.new(@client, children: res[:json][:data][:things].map { |t| unmarshal(t) }) end
js_model(res)
click to toggle source
Unmarshal frontend API-style models.
# File lib/redd/utilities/unmarshaller.rb, line 43 def js_model(res) # FIXME: deprecate this? this shouldn't be happening in the API, so this is better handled # in the respective classes. Models::BasicModel.new(@client, res[:json][:data]) if res[:json] && res[:json][:data] end