module Eco module CLI class Input MODES = [:both, :json, :value] attr_reader :mode def initialize(value, mode = :both) @mode = mode @mode = :both unless MODES.include?(mode) @doc = {} @doc['value'] = {} if self.value? @doc['json'] = {} if self.json? self.value = value end def to_h @doc end def json? @mode == :json || @mode = :both end def value? @mode == :value || @mode = :both end def json @doc['json'] if self.json? end def parse JSON.parse(self.json) if self.json? end def json=(value) @doc['value'] = value if self.value? @doc['json'] = to_json(value) if self.json? end def value return @doc['value'] if self.value? self.parse end def value=(value) @doc['value'] = value if self.value? @doc['json'] = to_json(value) if self.json? end def present?(key) self[key]&.present? end def empty? return @doc['value'].keys.length == 0 if self.value? @doc['json'].keys.length == 0 end # merging implies that @mode is equalized to the lesser # => :both.merge(:json) == :json ; :value.merge(:both) == :value mode # => :json.merge(:value) will raise an exception def merge(value) merge_hash(hash(value)) self end private def to_json(value) if value.respond_to?(:as_json) input.as_json elsif value.respond_to?(:to_json) value.to_json end end def doc_mode(doc) case doc when String doc = JSON.parse(doc) return nil unless doc.is_a?(Hash) doc_mode(doc) when CliInput doc.mode when Hash mod_json = doc.key?('json') mod_value = doc.key?('value') mod_json ? (mod_value ? :both : :json) : (mod_value ? :value : nil) end end def hash(value) case value when String JSON.parse(value) when CliInput value.to_h when Hash value end end end end end