Sha256: b3fb3f7d8ed5f427f092bcf0b5140148362f1ee36831ad522c2970b90c15a066

Contents?: true

Size: 786 Bytes

Versions: 2

Compression:

Stored size: 786 Bytes

Contents

require 'json'

module RubyJisho
  # Enumberable to store metadata and wrap Result objects cleanly
  class Results
    include Enumerable

    attr_reader :payload

    def initialize(payload)
      @payload = JSON.parse(payload, symbolize_names: true)
    end

    def meta
      payload.fetch(:meta, {})
    end

    def keys
      payload.keys
    end

    def each
      data.each { |r| yield r }
    end

    def method_missing(sym, *args, &block)
      if keys.include?(sym)
        payload.fetch(sym)
      else
        super
      end
    end

    def respond_to_missing?(method_name, include_private = false)
      keys.include?(method_name) || super
    end

    private

    def data
      payload.fetch(:data, [{}])
             .map { |r| Result.new(r) }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ruby_jisho-0.1.1 lib/ruby_jisho/results.rb
ruby_jisho-0.1.0 lib/ruby_jisho/results.rb