Sha256: f7ec3f6cc3001af447aec67989623a83206fd6ce4703a6adfbad7c8d62362ec8

Contents?: true

Size: 1.78 KB

Versions: 5

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module Arstotzka
  # @api private
  #
  # Class responsible for reading json / hash from instance
  class HashReader
    include Base

    # Returns a new instance of HashReader
    #
    # @overload iniitalize(options_hash = {})
    #   @param options_hash [Hash]
    #
    # @overload iniitalize(options)
    #   @param options [Arstotzka::Options]
    def initialize(options_hash = {})
      self.options = options_hash
    end

    # Retrieves the hash to be crawled from the instance
    #
    # @return [Hash]
    #
    # @example Simple Usage
    #   class Dummy
    #     def initialize(json = {})
    #       @json = json
    #     end
    #
    #     private
    #
    #     attr_reader :json
    #   end
    #
    #   hash = { key: 'value' }
    #   instance = Dummy.new(hash)
    #
    #   reader = Arstotzka::HashReader.new(
    #     instance: instance
    #   )
    #
    #   reader.hash # returns { key: 'value' }
    #
    # @example When fetching from class variable
    #   class ClassVariable
    #     def self.json=(json)
    #       @@json = json
    #     end
    #   end
    #
    #   hash = { key: 'value' }
    #   ClassVariable.json = hash
    #
    #   instance = ClassVariable.new
    #
    #   reader = Arstotzka::HashReader.new(
    #     instance: instance, json: :@@json
    #   )
    #
    #   reader.hash # returns { key: 'value' }
    def hash
      @hash ||= case json.to_s
                when /^@@.*/
                  instance.class.class_variable_get(json)
                when /^@.*/
                  then instance.instance_variable_get(json)
                else
                  instance.send(json)
                end
    end

    private

    attr_reader :options

    delegate :instance, to: :options
    delegate :json, to: :options
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
arstotzka-1.4.2 lib/arstotzka/hash_reader.rb
arstotzka-1.4.1 lib/arstotzka/hash_reader.rb
arstotzka-1.4.0 lib/arstotzka/hash_reader.rb
arstotzka-1.3.2 lib/arstotzka/hash_reader.rb
arstotzka-1.3.1 lib/arstotzka/hash_reader.rb