Sha256: 4fb1213ed881ec12dfb49a526b11ec7452c10cd5320398afa02bca445b46adfb

Contents?: true

Size: 1.04 KB

Versions: 5

Compression:

Stored size: 1.04 KB

Contents

require "ostruct"
require "delegate"

module PodcastIndex
  class Value < SimpleDelegator
    class << self
      FIND_ONE_ATTRIBUTES = %i[feed_id feed_url].freeze

      def find_by(attributes)
        match = (attributes.keys & FIND_ONE_ATTRIBUTES)
        raise ArgumentError, "Must supply one of the attributes: #{FIND_ONE_ATTRIBUTES}" unless match.present?
        raise ArgumentError, "Must supply only one of the attributes: #{FIND_ONE_ATTRIBUTES}" if match.length > 1

        send("find_by_#{match.first}", attributes[match.first])
      end

    private

      def find_by_feed_id(feed_id)
        response = Api::Value.by_feed_id(id: feed_id)
        from_response(response)
      end

      def find_by_feed_url(feed_url)
        response = Api::Value.by_feed_url(url: feed_url)
        from_response(response)
      end

      def from_response(response)
        value = response["value"].transform_keys(&:underscore)
        new(JSON.parse(value.to_json, object_class: OpenStruct)) # rubocop:disable Style/OpenStructUse
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
podcast_index-0.5.0 lib/podcast_index/value.rb
podcast_index-0.4.0 lib/podcast_index/value.rb
podcast_index-0.3.0 lib/podcast_index/value.rb
podcast_index-0.2.1 lib/podcast_index/value.rb
podcast_index-0.2.0 lib/podcast_index/value.rb