class Object

HACK

Public Class Methods

[](*args) click to toggle source
# File lib/nrser/labs/stash.rb, line 150
def self.[] *args
  new.merge! ::Hash[*args]
end
included(base) click to toggle source

Class Methods

# File lib/nrser/log/mixin.rb, line 46
def self.included base
  base.extend ClassMethods
  
  # Adds `.logger_measure_method`
  base.extend SemanticLogger::Loggable::ClassMethods
end

Public Instance Methods

Args(*args) click to toggle source
# File lib/nrser/rspex.rb, line 132
def Args *args
  NRSER::RSpex::Args.new args
end
I8(value = nil) click to toggle source

Method proxy to {I8.[]} allowing for different syntaxes.

# File lib/nrser/labs/i8.rb, line 121
def I8 value = nil
  I8[ value || yield ]
end
List(*args) click to toggle source
# File lib/nrser/rspex.rb, line 128
def List *args
  NRSER::RSpex::List.new args
end
[](key) click to toggle source

Same as Hash#[] where the key passed as argument can be either a string or a symbol:

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters['foo'] # => 1
counters[:foo]  # => 1
counters[:zoo]  # => nil
# File lib/nrser/labs/stash.rb, line 226
def [] key
  _raw_get convert_key( key )
end
Also aliased as: _raw_get
[]=(key, value) click to toggle source
# File lib/nrser/labs/stash.rb, line 124
def []= key, value
  put key, value
end
Also aliased as: store
_raw_get(key)
Alias for: []
as_array() click to toggle source

Call {NRSER.as_array} on `self`.

# File lib/nrser/core_ext/object.rb, line 42
def as_array
  NRSER.as_array self
end
as_hash(key = nil) click to toggle source

Calls {NRSER.as_hash} on `self` with the provided `key`.

# File lib/nrser/core_ext/object.rb, line 36
def as_hash key = nil
  NRSER.as_hash self, key
end
compact() click to toggle source
# File lib/nrser/labs/stash.rb, line 357
def compact
  dup.tap(&:compact!)
end
convert_value(value, options = {}) click to toggle source
# File lib/nrser/labs/stash.rb, line 114
def convert_value value, options = {}
  value
end
default(*args) click to toggle source

Same as Hash#default where the key passed as argument can be either a string or a symbol:

hash = ActiveSupport::HashWithIndifferentAccess.new(1)
hash.default                   # => 1

hash = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key }
hash.default                   # => nil
hash.default('foo')            # => 'foo'
hash.default(:foo)             # => 'foo'
Calls superclass method
# File lib/nrser/labs/stash.rb, line 269
def default(*args)
  super(*args.map { |arg| convert_key(arg) })
end
delete(key) click to toggle source

Removes the specified key from the hash.

Calls superclass method
# File lib/nrser/labs/stash.rb, line 328
def delete(key)
  super(convert_key(key))
end
dig(*args) click to toggle source

Same as Hash#dig where the key passed as argument can be either a string or a symbol:

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = { bar: 1 }

counters.dig('foo', 'bar')     # => 1
counters.dig(:foo, :bar)       # => 1
counters.dig(:zoo)             # => nil
Calls superclass method
# File lib/nrser/labs/stash.rb, line 253
def dig *args
  args[0] = convert_key( args[0] ) if args.size > 0
  super *args
end
dup() click to toggle source

Returns a shallow copy of the hash.

hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } })
dup  = hash.dup
dup[:a][:c] = 'c'

hash[:a][:c] # => "c"
dup[:a][:c]  # => "c"
# File lib/nrser/labs/stash.rb, line 291
def dup
  self.class.new(self).tap do |new_hash|
    set_defaults(new_hash)
  end
end
extractable_options?() click to toggle source

Returns true so that Array#extract_options! finds members of this class.

# File lib/nrser/labs/stash.rb, line 145
def extractable_options?
  true
end
falsy?() click to toggle source

See {NRSER.falsy?}.

# File lib/nrser/core_ext/object.rb, line 30
def falsy?
  NRSER.falsy? self
end
fetch(key, *extras) click to toggle source

Same as Hash#fetch where the key passed as argument can be either a string or a symbol:

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters.fetch('foo')          # => 1
counters.fetch(:bar, 0)        # => 0
counters.fetch(:bar) { |key| 0 } # => 0
counters.fetch(:zoo)           # => KeyError: key not found: "zoo"
Calls superclass method
# File lib/nrser/labs/stash.rb, line 240
def fetch key, *extras
  super convert_key(key), *extras
end
has_key?(key)
Alias for: key?
if(proc_able, &block) click to toggle source
# File lib/nrser/labs/i8/surjection.rb, line 15
def if proc_able, &block
  block.call( self ) if proc_able.to_proc.call( self )
end
include?(key)
Alias for: key?
is?(other) click to toggle source

Just an alias for `#equal?` that is easier for to remember.

@param [*] other

Something else.

@return [Boolean]

`true` if `self` and `other` are the same object.
# File lib/nrser/core_ext/object.rb, line 18
def is? other
  equal? other
end
key?(key) click to toggle source

Checks the hash for a key matching the argument passed in:

hash = ActiveSupport::HashWithIndifferentAccess.new
hash['key'] = 'value'
hash.key?(:key)  # => true
hash.key?('key') # => true
# File lib/nrser/labs/stash.rb, line 206
def key? key
  _raw_key? convert_key( key )
end
Also aliased as: include?, has_key?, member?
lazy_var(name, &block) click to toggle source

If the instance variable `name` is not defined, sets it to the result of `&block`. Always returns the instance variable's value.

Useful for lazy values that can be `nil` or `false`, since `||=` will always re-evaluate in their cases.

@param [Symbol] name

The name of the instance variable. Needs to have that `@` on the
front, like `:@x`.

@param [Proc<() => VALUE>] block

The block to call to get the value.

@return [VALUE]

The value of the instance variable.
# File lib/nrser/core_ext/object/lazy_var.rb, line 23
def lazy_var name, &block
  unless instance_variable_defined? name
    instance_variable_set name, block.call
  end
  
  instance_variable_get name
end
logger() click to toggle source

Gets the {NRSER::Log::Logger} for use in the instance. This will be the class logger from {ClassMethods#logger} unless the instance has a `#create_logger` method.

The `#create_logger` method is expected to return a {NRSER::Log::Logger} instance, which will be saved in the `@semantic_logger` instance variable for future use.

That method does not need to return a different logger for every instance

  • if you just want to have a different logger for all instance with a

different level or formatter or whatever, you can save it somewhere else and always return that same instance.

If you are dealing with frozen instances make sure to call `#logger` before you freeze (likely in the constructor). If you don't want to save the logger at all, just override this method itself.

This is a departure from {SemanticLogger::Loggable} that started because if the instance is frozen then attempting to set `@semantic_logger` will raise an error.

I also started ending up with classes that wanted to individually configure their loggers, so it seemed like we could take out two birds with this stone.

@return [SemanticLogger::Logger]

Instance level logger, if {ClassMethods.instance_logger?},
otherwise the class level logger from {ClassMethods#logger}.
# File lib/nrser/log/mixin.rb, line 86
def logger
  return @semantic_logger if @semantic_logger
  
  if respond_to?( :create_logger, true )
    @semantic_logger = begin
      create_logger
    rescue Exception => error
      self.class.logger.warn \
        "Error creating instance logger",
        { instance: self.inspect },
        error
      
      self.class.logger
    end
  else
    self.class.logger
  end
end
logger=(logger) click to toggle source

Replace instance level logger

# File lib/nrser/log/mixin.rb, line 107
def logger= logger
  @semantic_logger = logger
end
member?(key)
Alias for: key?
merge(hash, &block) click to toggle source

This method has the same semantics of update, except it does not modify the receiver but rather returns a new hash with indifferent access with the result of the merge.

# File lib/nrser/labs/stash.rb, line 300
def merge(hash, &block)
  dup.update(hash, &block)
end
merge!(other_hash, &block)
Alias for: update
merge_expectations(*expectations) click to toggle source

Merge “expectation” hashes by appending all clauses for each state.

@param [Array<Hash>] expectations

Splat of "expectation" hashes - see the examples.
# File lib/nrser/rspex.rb, line 50
def merge_expectations *expectations
  Hash.new { |result, state|
    result[state] = []
  }.tap { |result|
    expectations.each { |ex|
      ex.each { |state, clauses|
        result[state] += clauses.to_a
      }
    }
  }
end
msg(*args, &block) click to toggle source
# File lib/nrser/rspex.rb, line 123
def msg *args, &block
  NRSER::Message.from *args, &block
end
put(key, value) click to toggle source
# File lib/nrser/labs/stash.rb, line 119
def put key, value
  _convert_and_put key, value
end
reject(*args, &block) click to toggle source
# File lib/nrser/labs/stash.rb, line 347
def reject(*args, &block)
  return to_enum(:reject) unless block_given?
  dup.tap { |hash| hash.reject!(*args, &block) }
end
replace(other_hash) click to toggle source

Replaces the contents of this hash with other_hash.

h = { "a" => 100, "b" => 200 }
h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}
Calls superclass method
# File lib/nrser/labs/stash.rb, line 323
def replace(other_hash)
  super(self.class.new(other_hash))
end
reverse_merge(other_hash) click to toggle source

Like merge but the other way around: Merges the receiver into the argument and returns a new hash with indifferent access as result:

hash = ActiveSupport::HashWithIndifferentAccess.new
hash['a'] = nil
hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
Calls superclass method
# File lib/nrser/labs/stash.rb, line 310
def reverse_merge(other_hash)
  super(self.class.new(other_hash))
end
reverse_merge!(other_hash) click to toggle source

Same semantics as reverse_merge but modifies the receiver in-place.

# File lib/nrser/labs/stash.rb, line 315
def reverse_merge!(other_hash)
  replace(reverse_merge(other_hash))
end
select(*args, &block) click to toggle source

def stringify_keys!; self end def deep_stringify_keys!; self end def stringify_keys; dup end def deep_stringify_keys; dup end undef :symbolize_keys! undef :deep_symbolize_keys! def symbolize_keys; to_hash.symbolize_keys! end def deep_symbolize_keys; to_hash.deep_symbolize_keys! end def to_options!; self end

# File lib/nrser/labs/stash.rb, line 342
def select(*args, &block)
  return to_enum(:select) unless block_given?
  dup.tap { |hash| hash.select!(*args, &block) }
end
set_defaults(target) click to toggle source
# File lib/nrser/labs/stash.rb, line 134
def set_defaults(target)
  if default_proc
    target.default_proc = default_proc.dup
  else
    target.default = default
  end
end
store(key, value)

@!endgroup The Stuff You Care About # ************************************

Alias for: []=
thru() { |self| ... } click to toggle source

Yield `self`. Analogous to {#tap} but returns the result of the invoked block.

# File lib/nrser/core_ext/object.rb, line 5
def thru
  yield self
end
to_hash() click to toggle source

Convert to a regular hash with string keys.

# File lib/nrser/labs/stash.rb, line 362
def to_hash
  _new_hash = ::Hash.new
  set_defaults(_new_hash)

  each do |key, value|
    _new_hash[key] = convert_value(value, for: :to_hash)
  end
  _new_hash
end
transform_values(*args, &block) click to toggle source
# File lib/nrser/labs/stash.rb, line 352
def transform_values(*args, &block)
  return to_enum(:transform_values) unless block_given?
  dup.tap { |hash| hash.transform_values!(*args, &block) }
end
truthy?() click to toggle source

See {NRSER.truthy?}.

# File lib/nrser/core_ext/object.rb, line 24
def truthy?
  NRSER.truthy? self
end
unless(proc_able, &block) click to toggle source
# File lib/nrser/labs/i8/surjection.rb, line 19
def unless proc_able, &block
  block.call( self ) unless proc_able.to_proc.call( self )
end
unwrap(obj, context: nil) click to toggle source
# File lib/nrser/rspex.rb, line 115
def unwrap obj, context: nil
  if obj.is_a? Wrapper
    obj.unwrap context: context
  else
    obj
  end
end
update(other_hash) { |key, _raw_get( key ), value| ... } click to toggle source

Updates the receiver in-place, merging in the hash passed as argument:

hash_1 = ActiveSupport::HashWithIndifferentAccess.new
hash_1[:key] = 'value'

hash_2 = ActiveSupport::HashWithIndifferentAccess.new
hash_2[:key] = 'New Value!'

hash_1.update(hash_2) # => {"key"=>"New Value!"}

The argument can be either an ActiveSupport::HashWithIndifferentAccess or a regular Hash. In either case the merge respects the semantics of indifferent access.

If the argument is a regular hash with keys :key and +“key”+ only one of the values end up in the receiver, but which one is unspecified.

When given a block, the value for duplicated keys will be determined by the result of invoking the block with the duplicated key, the value in the receiver, and the value in other_hash. The rules for duplicated keys follow the semantics of indifferent access:

hash_1[:key] = 10
hash_2['key'] = 12
hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}

@param [Proc<(KEY, CURRENT, UPDATE) => VALUE>] block

Optional block to handle key conflicts.

@return [self]

# File lib/nrser/labs/stash.rb, line 186
def update other_hash, &block
  other_hash.to_hash.each_pair do |key, value|
    key = convert_key key
    if block && _raw_key?( key )
      value = yield key, _raw_get( key ), value
    end
    put key, value
  end
  self
end
Also aliased as: merge!
values_at(*indices) click to toggle source

Returns an array of the values at the specified indices:

hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:a] = 'x'
hash[:b] = 'y'
hash.values_at('a', 'b') # => ["x", "y"]
# File lib/nrser/labs/stash.rb, line 279
def values_at(*indices)
  indices.collect { |key| self[convert_key(key)] }
end
wrap(description = nil, &block) click to toggle source
# File lib/nrser/rspex.rb, line 105
def wrap description = nil, &block
  if block
    Wrapper.new description: description, &block
  else
    Wrapper.new description: description.to_s do
      send description
    end
  end
end