Module: NRSER

Defined in:
lib/nrser/proc.rb,
lib/nrser.rb,
lib/nrser/array.rb,
lib/nrser/rspex.rb,
lib/nrser/errors.rb,
lib/nrser/logger.rb,
lib/nrser/no_arg.rb,
lib/nrser/string.rb,
lib/nrser/binding.rb,
lib/nrser/message.rb,
lib/nrser/version.rb,
lib/nrser/merge_by.rb,
lib/nrser/types/in.rb,
lib/nrser/exception.rb,
lib/nrser/hash/bury.rb,
lib/nrser/collection.rb,
lib/nrser/enumerable.rb,
lib/nrser/meta/props.rb,
lib/nrser/temp/where.rb,
lib/nrser/text/lines.rb,
lib/nrser/open_struct.rb,
lib/nrser/tree/leaves.rb,
lib/nrser/types/array.rb,
lib/nrser/types/pairs.rb,
lib/nrser/types/paths.rb,
lib/nrser/types/labels.rb,
lib/nrser/object/truthy.rb,
lib/nrser/tree/map_tree.rb,
lib/nrser/object/as_hash.rb,
lib/nrser/text/word_wrap.rb,
lib/nrser/tree/transform.rb,
lib/nrser/hash/deep_merge.rb,
lib/nrser/hash/slice_keys.rb,
lib/nrser/meta/props/base.rb,
lib/nrser/meta/props/prop.rb,
lib/nrser/object/as_array.rb,
lib/nrser/refinements/set.rb,
lib/nrser/tree/map_leaves.rb,
lib/nrser/hash/except_keys.rb,
lib/nrser/meta/class_attrs.rb,
lib/nrser/refinements/hash.rb,
lib/nrser/refinements/tree.rb,
lib/nrser/text/indentation.rb,
lib/nrser/tree/each_branch.rb,
lib/nrser/refinements/array.rb,
lib/nrser/refinements/types.rb,
lib/nrser/string/looks_like.rb,
lib/nrser/temp/unicode_math.rb,
lib/nrser/tree/map_branches.rb,
lib/nrser/refinements/object.rb,
lib/nrser/refinements/string.rb,
lib/nrser/refinements/symbol.rb,
lib/nrser/hash/stringify_keys.rb,
lib/nrser/hash/symbolize_keys.rb,
lib/nrser/hash/transform_keys.rb,
lib/nrser/refinements/binding.rb,
lib/nrser/refinements/pathname.rb,
lib/nrser/refinements/exception.rb,
lib/nrser/rspex/shared_examples.rb,
lib/nrser/refinements/enumerable.rb,
lib/nrser/refinements/enumerator.rb,
lib/nrser/refinements/open_struct.rb,
lib/nrser/hash/guess_label_key_type.rb

Overview

Definitions

Defined Under Namespace

Modules: Collection, Meta, RSpex, Refinements, Types, UnicodeMath, Version Classes: AbstractMethodError, ConflictError, Lines, Logger, Message, NoArg, SendSerializer, Where

String Functions collapse

WHITESPACE_RE =
/\A[[:space:]]*\z/
UNICODE_ELLIPSIS =
'…'

Text collapse

INDENT_RE =

Constants

/\A[\ \t]*/
INDENT_TAG_MARKER =
"\x1E"
INDENT_TAG_SEPARATOR =
"\x1F"

Constant Summary collapse

ROOT =
( Pathname.new(__FILE__).dirname / '..' ).expand_path
NO_ARG =
NoArg.instance
VERSION =
"0.0.27"
TRUTHY_STRINGS =

Down-cased versions of strings that are considered to communicate truth.

Set.new [
  'true',
  't',
  'yes',
  'y',
  'on',
  '1',
]
FALSY_STRINGS =

Down-cased versions of strings that are considered to communicate false.

Set.new [
  'false',
  'f',
  'no',
  'n',
  'off',
  '0',
  '',
]
JSON_ARRAY_RE =

Constants

/\A\s*\[.*\]\s*\z/m

String Functions collapse

Text collapse

Class Method Summary collapse

Class Method Details

.as_array(value) ⇒ Array

Return an array given any value in the way that makes most sense:

  1. If ‘value` is an array, return it.

  2. If ‘value` is `nil`, return `[]`.

  3. If ‘value` responds to `#to_a`, try calling it. If it succeeds, return that.

  4. Return an array with ‘value` as it’s only item.

Refinement


Added to ‘Object` in `nrser/refinements`.

Parameters:

  • value (Object)

Returns:

  • (Array)


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/nrser/object/as_array.rb', line 23

def self.as_array value
  return value if value.is_a? Array
  return [] if value.nil?
  
  if value.respond_to? :to_a
    begin
      return value.to_a
    rescue
    end
  end
  
  [value]
end

.as_hash(value, key = nil) ⇒ Hash

TODO:

It might be nice to have a ‘check` option that ensures the resulting hash has a value for `key`.

Treat the value as the value for ‘key` in a hash if it’s not already a hash and can’t be converted to one:

  1. If the value is a ‘Hash`, return it.

  2. If ‘value` is `nil`, return `{}`.

  3. If the value responds to ‘#to_h` and `#to_h` succeeds, return the resulting hash.

  4. Otherwise, return a new hash where ‘key` points to the value. **`key` MUST be provided in this case.**

Useful in method overloading and similar situations where you expect a hash that may specify a host of options, but want to allow the method to be called with a single value that corresponds to a default key in that option hash.

Refinement


Added to ‘Object` in `nrser/refinements`.

Example Time!


Say you have a method ‘m` that handles a hash of HTML options that can look something like

{class: 'address', data: {confirm: 'Really?'}}

And can call ‘m` like

m({class: 'address', data: {confirm: 'Really?'}})

but often you are just dealing with the ‘:class` option. You can use as_hash to accept a string and treat it as the `:class` key:

using NRSER

def m opts
  opts = opts.as_hash :class
  # ...
end

If you pass a hash, everything works normally, but if you pass a string ‘’address’‘ it will be converted to `’address’‘.

About ‘#to_h` Support


Right now, as_hash also tests if ‘value` responds to `#to_h`, and will try to call it, using the result if it doesn’t raise. This lets it deal with Ruby’s “I used to be a Hash until someone mapped me” values like ‘[[:class, ’address’]]‘. I’m not sure if this is the best approach, but I’m going to try it for now and see how it pans out in actual usage.

Parameters:

  • value (Object)

    The value that we want to be a hash.

  • key (Object) (defaults to: nil)
    default nil

    The key that ‘value` will be stored under in the result if `value` is not a hash or can’t be turned into one via ‘#to_h`. If this happens this value can NOT be `nil` or an `ArgumentError` is raised.

Returns:

  • (Hash)

Raises:

  • (ArgumentError)

    If it comes to constructing a new Hash with ‘value` as a value and no argument was provided



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/nrser/object/as_hash.rb', line 80

def self.as_hash value, key = nil
  return value if value.is_a? Hash
  return {} if value.nil?
  
  if value.respond_to? :to_h
    begin
      return value.to_h
    rescue
    end
  end
  
  # at this point we need a key argument
  if key.nil?
    raise ArgumentError,
          "Need key to construct hash with value #{ value.inspect }, " +
          "found nil."
  end
  
  {key => value}
end

.bury!(hash, key_path, value, parsed_key_type: :guess, clobber: false, create_arrays_for_unsigned_keys: false) ⇒ return_type

The opposite of ‘#dig` - set a value at a deep key path, creating necessary structures along the way and optionally clobbering whatever’s in the way to achieve success.

Parameters:

  • hash (Hash)

    Hash to bury the value in.

  • key_path (Array | #to_s)
    • When an Array, each entry is used exactly as-is for each key.

    • Otherwise, the ‘key_path` is converted to a string and split by `.` to produce the key array, and the actual keys used depend on the `parsed_key_type` option.

  • value (Object)

    The value to set at the end of the path.

  • parsed_key_type: (Class | :guess) (defaults to: :guess)

    How to handle parsed key path segments:

    • ‘String` - use the strings that naturally split from a parsed key path.

      Note that this is the *String class itself, not a value that is a String*.

    • ‘Symbol` - convert the strings that are split from the key path to symbols.

      Note that this is the *Symbol class itself, not a value that is a Symbol*.“

    • ‘:guess` (default) -

Returns:

  • (return_type)

    @todo Document return value.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/nrser/hash/bury.rb', line 48

def bury! hash,
          key_path,
          value,
          parsed_key_type: :guess,
          clobber: false,
          create_arrays_for_unsigned_keys: false
  
  # Parse the key if it's not an array
  unless key_path.is_a?( Array )
    key_path = key_path.to_s.split '.'
    
    # Convert the keys to symbols now if that's what we want to use
    if parsed_key_type == Symbol
      key_path.map! &:to_sym
    end
  end
  
  _internal_bury! \
    hash,
    key_path,
    value,
    guess_key_type: ( parsed_key_type == :guess ),
    clobber: clobber,
    create_arrays_for_unsigned_keys: create_arrays_for_unsigned_keys
end

.chainer(mappable, publicly: true) ⇒ Proc

Note:

‘mappable“ entries are mapped into messages when #to_chain is called, meaning subsequent changes to `mappable` **will not** affect the returned proc.

Map *each entry* in ‘mappable` to a Message and return a Proc that accepts a single `receiver` argument and reduces it by applying each message in turn.

In less precise terms: create a proc that chains the entries as methods calls.

Examples:

Equivalent of ‘Time.now.to_i`


NRSER::chainer( [:now, :to_i] ).call Time
# => 1509628038

Returns:

  • (Proc)


108
109
110
111
112
113
114
115
116
# File 'lib/nrser/proc.rb', line 108

def self.chainer mappable, publicly: true
  messages = mappable.map { |value| message *value }
  
  ->( receiver ) {
    messages.reduce( receiver ) { |receiver, message|
      message.send_to receiver, publicly: publicly
    }
  }
end

.collection?(obj) ⇒ Boolean

test if an object is considered a collection.

Parameters:

  • obj (Object)

    object to test

Returns:

  • (Boolean)

    true if ‘obj` is a collection.



28
29
30
# File 'lib/nrser/collection.rb', line 28

def collection? obj
  Collection::STDLIB.any? {|cls| obj.is_a? cls} || obj.is_a?(Collection)
end

.common_prefix(strings) ⇒ Object

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nrser/string.rb', line 31

def common_prefix strings
  raise ArgumentError.new("argument can't be empty") if strings.empty?
  
  sorted = strings.sort
  
  i = 0
  
  while sorted.first[i] == sorted.last[i] &&
        i < [sorted.first.length, sorted.last.length].min
    i = i + 1
  end
  
  sorted.first[0...i]
end

.constantize(camel_cased_word) ⇒ Object Also known as: to_const

Get the constant identified by a string.

Lifted from ActiveSupport.

Examples:


SomeClass == NRSER.constantize(SomeClass.name)

Parameters:

  • camel_cased_word (String)

    The constant’s camel-cased, double-colon-separated “name”, like “NRSER::Types::Array”.

Returns:

  • (Object)

Raises:

  • (NameError)

    When the name is not in CamelCase or is not initialized.



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/nrser/string.rb', line 260

def constantize(camel_cased_word)
  names = camel_cased_word.split('::')

  # Trigger a built-in NameError exception including the ill-formed constant in the message.
  Object.const_get(camel_cased_word) if names.empty?

  # Remove the first blank element in case of '::ClassName' notation.
  names.shift if names.size > 1 && names.first.empty?

  names.inject(Object) do |constant, name|
    if constant == Object
      constant.const_get(name)
    else
      candidate = constant.const_get(name)
      next candidate if constant.const_defined?(name, false)
      next candidate unless Object.const_defined?(name)

      # Go down the ancestors to check if it is owned directly. The check
      # stops when we reach Object or the end of ancestors tree.
      constant = constant.ancestors.inject do |const, ancestor|
        break const    if ancestor == Object
        break ancestor if ancestor.const_defined?(name, false)
        const
      end

      # owner is in Object, so raise
      constant.const_get(name, false)
    end
  end
end

.dedent(text, ignore_whitespace_lines: true) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/nrser/text/indentation.rb', line 69

def self.dedent text, ignore_whitespace_lines: true
  return text if text.empty?
  
  all_lines = text.lines
  
  indent_significant_lines = if ignore_whitespace_lines
    all_lines.reject { |line| whitespace? line }
  else
    all_lines
  end
  
  indent = find_indent indent_significant_lines
  
  return text if indent.empty?
  
  all_lines.map { |line|
    if line.start_with? indent
      line[indent.length..-1]
    elsif line.end_with? "\n"
      "\n"
    else
      ""
    end
  }.join
end

.deep_merge(base_hash, other_hash, &block) ⇒ Hash

Returns a new hash created by recursively merging ‘other_hash` on top of `base_hash`.

Adapted from ActiveSupport.

Parameters:

  • base_hash (Hash)

    Base hash - it’s values will be overwritten by any key paths shared with the other hash.

  • other_hash (Hash)

    “Update” hash - it’s values will overwrite values at the same key path in the base hash.

    I don’t love the name; just went with what ActiveSupport used.

Returns:

  • (Hash)

    New merged hash.

See Also:



27
28
29
# File 'lib/nrser/hash/deep_merge.rb', line 27

def self.deep_merge base_hash, other_hash, &block
  deep_merge! base_hash.dup, other_hash, &block
end

.deep_merge!(base_hash, other_hash, &block) ⇒ Hash

Same as deep_merge, but modifies ‘base_hash`.

Returns:

  • (Hash)

    The mutated base hash.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nrser/hash/deep_merge.rb', line 37

def self.deep_merge! base_hash, other_hash, &block
  other_hash.each_pair do |current_key, other_value|
    this_value = base_hash[current_key]

    base_hash[current_key] = if this_value.is_a?(Hash) && 
                                other_value.is_a?(Hash)
      deep_merge this_value, other_value, &block
    else
      if block_given? && base_hash.key?( current_key )
        block.call(current_key, this_value, other_value)
      else
        other_value
      end
    end
  end

  base_hash
end

.each(object) { ... } ⇒ Object

Yield on each element of a collection or on the object itself if it’s not a collection. avoids having to normalize to an array to iterate over something that may be an object OR a collection of objects.

NOTE Implemented for our idea of a collection instead of testing

for response to `#each` (or similar) to avoid catching things
like {IO} instances, which include {Enumerable} but are 
probably not what is desired when using {NRSER.each}
(more likely that you mean "I expect one or more files" than
"I expect one or more strings which may be represented by
lines in an open {File}").

Parameters:

  • object (Object)

    Target object.

Yields:

  • Each element of a collection or the target object itself.

Returns:

  • (Object)

    ‘object` param.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/nrser/collection.rb', line 54

def each object, &block
  if collection? object
    # We need to test for response because {OpenStruct} *will* respond to
    # #each because *it will respond to anything* (which sucks), but it 
    # will return `false` for `respond_to? :each` and the like, and this
    # behavior could be shared by other collection objects, so it seems 
    # like a decent idea.
    if object.respond_to? :each_pair
      object.each_pair &block
    elsif object.respond_to? :each
      object.each &block
    else
      raise TypeError.squished "        Object \#{ obj.inpsect } does not respond to #each or #each_pair\n      END\n    end\n  else\n    block.call object\n  end\n  object\nend\n"

.each_branch(tree) {|key, value| ... } ⇒ Enumerator, #each_pair | (#each_index & #each_with_index)

Note:

Not sure what will happen if the tree has circular references!

Enumerate over the immediate “branches” of a structure that can be used to compose our idea of a tree: nested hash-like and array-like structures like you would get from parsing a JSON document.

Written and tested against Hash and Array instances, but should work with anything hash-like that responds to ‘#each_pair` appropriately or array-like that responds to `#each_index` and `#each_with_index`.

Parameters:

  • tree (#each_pair | (#each_index & #each_with_index))

    Structure representing a tree via hash-like and array-like containers.

Yield Parameters:

  • key (Object)

    The first yielded param is the key or index for the value branch at the top level of ‘tree`.

  • value (Object)

    The second yielded param is the branch at the key or index at the top level of ‘tree`.

Yield Returns:

  • Ignored.

Returns:

  • (Enumerator)

    If no block is provided.

  • (#each_pair | (#each_index & #each_with_index))

    If a block is provided, the result of the ‘#each_pair` or `#each_with_index` call.

Raises:

  • (NoMethodError)

    If ‘tree` does not respond to `#each_pair` or to `#each_index` and `#each_with_index`.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/nrser/tree/each_branch.rb', line 41

def self.each_branch tree, &block
  if tree.respond_to? :each_pair
    # Hash-like
    tree.each_pair &block
    
  elsif tree.respond_to? :each_index
    # Array-like... we test for `each_index` because - unintuitively - 
    # `#each_with_index` is a method of {Enumerable}, meaning that {Set}
    # responds to it, though sets are unordered and the values can't be
    # accessed via those indexes. Hence we look for `#each_index`, which 
    # {Set} does not respond to.
    
    if block.nil?        
      index_enumerator = tree.each_with_index
      
      Enumerator.new( index_enumerator.size ) { |yielder|
        index_enumerator.each { |value, index|
          yielder.yield [index, value]
        }
      }
    else
      tree.each_with_index.map { |value, index|
        block.call [index, value]
      }
    end
    
  else
    raise NoMethodError.new NRSER.squish "      `tree` param must respond to `#each_pair` or `#each_index`,\n      found \#{ tree.inspect }\n    END\n    \n  end # if / else\nend\n"

.ellipsis(string, max, omission: UNICODE_ELLIPSIS) ⇒ String

Cut the middle out of a string and stick an ellipsis in there instead.

Parameters:

  • string (String)

    Source string.

  • max (Fixnum)

    Max length to allow for the output string.

  • omission: (String) (defaults to: UNICODE_ELLIPSIS)

    The string to stick in the middle where original contents were removed. Defaults to the unicode ellipsis since I’m targeting the CLI at the moment and it saves precious characters.

Returns:

  • (String)

    String of at most ‘max` length with the middle chopped out if needed to do so.



141
142
143
144
145
146
147
148
149
150
# File 'lib/nrser/string.rb', line 141

def ellipsis string, max, omission: UNICODE_ELLIPSIS
  return string unless string.length > max
  
  trim_to = max - omission.length
  
  start = string[0, (trim_to / 2) + (trim_to % 2)]
  finish = string[-( (trim_to / 2) - (trim_to % 2) )..-1]
  
  start + omission + finish
end

.enumerate_as_values(enum) ⇒ Enumerator

Create an Enumerator that iterates over the “values” of an Enumerable ‘enum`. If `enum` responds to `#each_value` than we return that. Otherwise, we return `#each_entry`.

Parameters:

  • enum (Enumerable)

Returns:

  • (Enumerator)

Raises:

  • (TypeError)

    If ‘enum` doesn’t respond to ‘#each_value` or `#each_entry`.



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/nrser/enumerable.rb', line 189

def enumerate_as_values enum
  # NRSER.match enum,
  #   t.respond_to(:each_value), :each_value.to_proc,
  #   t.respond_to(:each_entry), :each_entry.to_proc
  # 
  if enum.respond_to? :each_value
    enum.each_value
  elsif enum.respond_to? :each_entry
    enum.each_entry
  else
    raise TypeError.squished "      Expected `enum` arg to respond to :each_value or :each_entry,\n      found \#{ enum.inspect }\n    END\n  end\nend\n"

.erb(bnd, str) ⇒ Object Also known as: template



6
7
8
9
10
11
12
13
14
15
# File 'lib/nrser/binding.rb', line 6

def erb bnd, str
  require 'erb'
  
  filter_repeated_blank_lines(
    with_indent_tagged( dedent( str ) ) { |tagged_str|
      ERB.new( tagged_str ).result( bnd )
    },
    remove_leading: true
  )
end

.except_keys(hash, *keys) ⇒ Hash

Returns a new hash without ‘keys`.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

    Source hash.

Returns:

  • (Hash)

See Also:



36
37
38
# File 'lib/nrser/hash/except_keys.rb', line 36

def self.except_keys hash, *keys
  except_keys! hash.dup, *keys
end

.except_keys!(hash, *keys) ⇒ Hash

Removes the given keys from hash and returns it.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

    Hash to mutate.

Returns:

  • (Hash)

See Also:



17
18
19
20
# File 'lib/nrser/hash/except_keys.rb', line 17

def self.except_keys! hash, *keys
  keys.each { |key| hash.delete(key) }
  hash
end

.extract_from_array!(array, &block) ⇒ Object

A destructive partition.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/nrser/array.rb', line 17

def self.extract_from_array! array, &block
  extracted = []
  array.reject! { |entry|
    test = block.call entry
    if test
      extracted << entry
    end
    test
  }
  extracted
end

.falsy?(object) ⇒ Boolean

Opposite of truthy?.

Parameters:

  • object (Nil, String)

    Value to test.

Returns:

  • (Boolean)

    The negation of truthy?.



68
69
70
# File 'lib/nrser/object/truthy.rb', line 68

def self.falsy? object
  ! truthy?(object)
end

.filter_repeated_blank_lines(str, remove_leading: false) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/nrser/string.rb', line 47

def filter_repeated_blank_lines str, remove_leading: false
  out = []
  lines = str.lines
  skipping = remove_leading
  str.lines.each do |line|
    if line =~ /^\s*$/
      unless skipping
        out << line
      end
      skipping = true
    else
      skipping = false
      out << line
    end
  end
  out.join
end

.find_bounded(enum, bounds, &block) ⇒ return_type

Find all entries in an Enumerable for which ‘&block` returns a truthy value, then check the amount of results found against the NRSER::Types.length created from `bounds`, raising a TypeError if the results’ length doesn’t satisfy the bounds type.

Parameters:

  • enum (Enumerable)

    The entries to search and check.

  • []

Returns:

  • (return_type)

    @todo Document return value.

Raises:



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/nrser/enumerable.rb', line 77

def find_bounded enum, bounds, &block
  NRSER::Types.
    length(bounds).
    check(enum.find_all &block) { |type:, value:|
      NRSER.dedent "        \n        Length of found elements (\#{ value.length }) FAILED to \n        satisfy \#{ type.to_s }\n        \n        Found:\n          \#{ NRSER.indent value.pretty_inspect }\n        \n        Enumerable:\n          \#{ NRSER.indent enum.pretty_inspect }\n        \n      END\n    }\nend\n"

.find_indent(text) ⇒ Object

Functions



31
32
33
# File 'lib/nrser/text/indentation.rb', line 31

def self.find_indent text
  common_prefix lines( text ).map { |line| line[INDENT_RE] }
end

.find_only(enum, &block) ⇒ return_type

TODO:

Document find_only method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



105
106
107
# File 'lib/nrser/enumerable.rb', line 105

def find_only enum, &block
  find_bounded(enum, 1, &block).first
end

.format_exception(e) ⇒ Object



3
4
5
# File 'lib/nrser/exception.rb', line 3

def format_exception e
  "#{ e.message } (#{ e.class }):\n  #{ e.backtrace.join("\n  ") }"
end

.guess_label_key_type(keyed) ⇒ nil, Class

Guess which type of “label” key - strings or symbols - a hash (or other object that responds to ‘#keys` and `#empty`) uses.

Parameters:

  • keyed (#keys & #empty)

    Hash or similar object that responds to ‘#keys` and `#empty` to guess about.

Returns:

  • (nil)

    If we can’t determine the type of “label” keys are used (there aren’t any or there is a mix).

  • (Class)

    If we can determine that String or Symbol keys are exclusively used returns that class.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/nrser/hash/guess_label_key_type.rb', line 21

def self.guess_label_key_type keyed
  # We can't tell shit if the hash is empty
  return nil if keyed.empty?
  
  name_types = keyed.
    keys.
    map( &:class ).
    select { |klass| klass == String || klass == Symbol }.
    uniq
  
  return name_types[0] if name_types.length == 1
  
  # There are both string and symbol keys present, we can't guess
  nil
end

.indent(text, amount = 2, indent_string: nil, indent_empty_lines: false, skip_first_line: false) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/nrser/text/indentation.rb', line 45

def self.indent text,
                amount = 2,
                indent_string: nil,
                indent_empty_lines: false,
                skip_first_line: false
  if skip_first_line
    lines = self.lines text
    
    lines.first + indent(
      rest( lines ).join,
      amount,
      indent_string: indent_string,
      skip_first_line: false
    )
    
  else
    indent_string = indent_string || text[/^[ \t]/] || ' '
    re = indent_empty_lines ? /^/ : /^(?!$)/
    text.gsub re, indent_string * amount
    
  end
end

.indent_tag(text, marker: INDENT_TAG_MARKER, separator: INDENT_TAG_SEPARATOR) ⇒ String

Tag each line of ‘text` with special marker characters around it’s leading indent so that the resulting text string can be fed through an interpolation process like ERB that may inject multiline strings and the result can then be fed through indent_untag to apply the correct indentation to the interpolated lines.

Each line of ‘text` is re-formatted like:

"<marker><leading_indent><separator><line_without_leading_indent>"

‘marker` and `separator` can be configured via keyword arguments, but they

default to:
  • ‘marker` - INDENT_TAG_MARKER, the no-printable ASCII *record separator* (ASCII character 30, “x1E” / “u001E”).

  • ‘separator` - INDENT_TAG_SEPARATOR, the non-printable ASCII *unit separator* (ASCII character 31, “x1F” / “u001F”)

Examples:

With default marker and separator

NRSER.indent_tag "    hey there!"
# => "\x1E    \x1Fhey there!"

Parameters:

  • text (String)

    String text to indent tag.

  • marker: (String) (defaults to: INDENT_TAG_MARKER)

    Special string to mark the start of tagged lines. If interpolated text lines start with this string you’re going to have a bad time.

  • separator: (String) (defaults to: INDENT_TAG_SEPARATOR)

    Special string to separate the leading indent from the rest of the line.

Returns:

  • (String)

    Tagged text.



135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/nrser/text/indentation.rb', line 135

def self.indent_tag text,
                    marker: INDENT_TAG_MARKER,
                    separator: INDENT_TAG_SEPARATOR
  text.lines.map { |line|
    indent = if match = INDENT_RE.match( line )
      match[0]
    else
      ''
    end
    
    "#{ marker }#{ indent }#{ separator }#{ line[indent.length..-1] }"
  }.join
end

.indent_untag(text, marker: INDENT_TAG_MARKER, separator: INDENT_TAG_SEPARATOR) ⇒ String

Reverse indent tagging that was done via indent_tag, indenting any untagged lines to the same level as the one above them.

Parameters:

  • text (String)

    Tagged text string.

  • marker: (String) (defaults to: INDENT_TAG_MARKER)

    Must be the marker used to tag the text.

  • separator: (String) (defaults to: INDENT_TAG_SEPARATOR)

    Must be the separator used to tag the text.

Returns:

  • (String)

    Final text with interpolation and indent correction.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/nrser/text/indentation.rb', line 165

def self.indent_untag text,
                      marker: INDENT_TAG_MARKER,
                      separator: INDENT_TAG_SEPARATOR
  
  current_indent = ''
  
  text.lines.map { |line|
    if line.start_with? marker
      current_indent, line = line[marker.length..-1].split( separator, 2 )
    end
    
    current_indent + line
    
  }.join
  
end

.indented?(text) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/nrser/text/indentation.rb', line 36

def self.indented? text
  !( find_indent( text ).empty? )
end

.lazy_filter_repeated_blank_lines(source, remove_leading: false) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/nrser/string.rb', line 66

def lazy_filter_repeated_blank_lines source, remove_leading: false
  skipping = remove_leading
  
  source = source.each_line if source.is_a? String
  
  Enumerator::Lazy.new source do |yielder, line|
    if line =~ /^\s*$/
      unless skipping
        yielder << line
      end
      skipping = true
    else
      skipping = false
      yielder << line
    end
  end
  
end

.leaves(tree) ⇒ Hash<Array, Object>

Create a new hash where all the values are the scalar “leaves” of the possibly nested ‘hash` param. Leaves are keyed by “key path” arrays representing the sequence of keys to dig that leaf out of the has param.

In abstract, if ‘h` is the `hash` param and

l = NRSER.leaves h

then for each key ‘k` and corresponding value `v` in `l`

h.dig( *k ) == v

Examples:

Simple “flat” hash


NRSER.leaves( {a: 1, b: 2} )
=> {
  [:a] => 1,
  [:b] => 2,
}

Nested hash


NRSER.leaves(
  1 => {
    name: 'Neil',
    fav_color: 'blue',
  },
  2 => {
    name: 'Mica',
    fav_color: 'red',  
  }
)
# => {
#   [1, :name]      => 'Neil',
#   [1, :fav_color] => 'blue',
#   [2, :name]      => 'Mica',
#   [2, :fav_color] => 'red',
# }

Parameters:

  • tree (#each_pair | (#each_index & #each_with_index))

Returns:

  • (Hash<Array, Object>)


51
52
53
54
55
# File 'lib/nrser/tree/leaves.rb', line 51

def leaves tree
  {}.tap { |results|
    _internal_leaves tree, path: [], results: results
  }
end

.lines(text) ⇒ Object

Functions



41
42
43
44
45
46
47
48
49
50
# File 'lib/nrser/text/lines.rb', line 41

def self.lines text
  case text
  when String
    text.lines
  when Array
    text
  else
    raise TypeError, "Expected String or Array, found #{ text.class.name }"
  end
end

.looks_like_json_array?(string) ⇒ Boolean

Test if a string looks like it might encode an array in JSON format by seeing if it’s first non-whitespace character is ‘[` and last non-whitespace character is `]`.

Parameters:

  • string (String)

    String to test.

Returns:

  • (Boolean)

    ‘true` if we think `string` encodes a JSON array.



44
45
46
# File 'lib/nrser/string/looks_like.rb', line 44

def looks_like_json_array? string
  !!( string =~ JSON_ARRAY_RE )
end

.map(object) { ... } ⇒ Object

If ‘object` is a collection, calls `#map` with the block. Otherwise, applies block to the object and returns the result.

See note in each for discussion of why this tests for a collection instead of duck-typing ‘#map`.

Parameters:

  • object (Object)

    Target object.

Yields:

  • Each element of a collection or the target object itself.

Returns:

  • (Object)

    The result of mapping or applying the block.



92
93
94
95
96
97
98
# File 'lib/nrser/collection.rb', line 92

def map object, &block
  if collection? object
    object.map &block
  else
    block.call object
  end
end

.map_branches(tree) {|key, value| ... } ⇒ Array | Hash

TODO:

Might be nice to have an option to preserve the tree class that creates a new instance of whatever it was and populates that, though I could see this relying on problematic assumptions and producing confusing results depending on the actual classes.

Maybe this could be encoded in a mixin that we would detect or something.

Note:

Not sure what will happen if the tree has circular references!

Map the immediate “branches” of a structure that can be used to compose our idea of a tree: nested hash-like and array-like structures like you would get from parsing a JSON document.

The ‘block` MUST return a pair (Array of length 2), the first value of which is the key or index in the new Hash or Array.

These pairs are then converted into a Hash or Array depending on it ‘tree` was NRSER::Types.hash_like or NRSER::Types.array_like, and that value is returned.

Uses each_branch internally.

Written and tested against Hash and Array instances, but should work with anything:

  1. hash-like that responds to ‘#each_pair` appropriately.

  2. array-like that responds to ‘#each_index` and `#each_with_index` appropriately.

Parameters:

  • tree (#each_pair | (#each_index & #each_with_index))

    Structure representing a tree via hash-like and array-like containers.

Yield Parameters:

  • key (Object)

    The first yielded param is the key or index for the value branch at the top level of ‘tree`.

  • value (Object)

    The second yielded param is the branch at the key or index at the top level of ‘tree`.

Yield Returns:

  • (Array)

    Pair of key (/index) in new array or hash followed by value.

Returns:

  • (Array | Hash)

    If no block is provided.

Raises:

  • (NoMethodError)

    If ‘tree` does not respond to `#each_pair` or to `#each_index` and `#each_with_index`.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/nrser/tree/map_branches.rb', line 72

def self.map_branches tree, &block
  if block.nil?
    raise ArgumentError, "Must provide block"
  end
  
  pairs = each_branch( tree ).map &block
  
  Types.match tree,
    Types.hash_like, ->( _ ) {
      pairs.to_h
    },
    
    Types.array_like, ->( _ ) {
      pairs.each_with_object( [] ) { |(index, value), array|
        array[index] = value
      }
    }
end

.map_leaves(tree, &block) ⇒ Object



8
9
10
11
12
# File 'lib/nrser/tree/map_leaves.rb', line 8

def map_leaves tree, &block
  NRSER::Types.tree.check tree
  
  _internal_map_leaves tree, key_path: [], &block
end

.map_tree(tree, prune: false) {|element| ... } ⇒ Object

Note:

Array indexes **are not mapped** through ‘block` and can not be changed via this method. This makes it easier to do things like “convert all the integers to strings” when you mean the data entries, not the array indexes (which would fail since the new array wouldn’t accept string indices).

If you don’t want to map hash keys use map_leaves.

Recursively descend through a tree mapping all non-structural elements

hash keys and values, as well as array entries - through ‘block` to produce a new structure.

Useful when you want to translate pieces of a tree structure depending on their type or some other property that can be determined *from the element alone* - ‘block` receives only the value as an argument, no location information (because it’s weirder to represent for keys and I didn’t need it for the transformer stuff this was written for).

See the specs for examples. Used in transformer.

Parameters:

  • prune: (Boolean) (defaults to: false)

    When ‘true`, prunes out values whose labels end with `?` and values are `nil`.

  • tree (#each_pair | (#each_index & #each_with_index))

    Structure representing a tree via hash-like and array-like containers.

Yield Parameters:

  • element (Object)

    Anything reached from the root that is not structural (hash-like or array-like), including / inside hash keys (though array indexes are not passed).



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/nrser/tree/map_tree.rb', line 46

def self.map_tree tree, prune: false, &block
  # TODO type check tree?
  
  mapped = tree.map { |element|
    # Recur if `element` is a tree.
    # 
    # Since `element` will be an {Array} of `key`, `value` when `tree` is a 
    # {Hash} (or similar), this will descend into hash keys that are also
    # trees, as well as into hash values and array entries.
    # 
    if Types.tree.test element
      map_tree element, prune: prune, &block
    else
      # When we've run out of trees, finally pipe through the block:
      block.call element
    end
  }
  
  # If `tree` is hash-like, we want to convert the array of pair arrays 
  # back into a hash.
  if Types.hash_like.test tree
    if prune
      pruned = {}
      
      mapped.each { |key, value|
        if  Types.label.test( key ) &&
            key.to_s.end_with?( '?' )
          unless value.nil?
            new_key = key.to_s[0..-2]
            
            if key.is_a?( Symbol )
              new_key = new_key.to_sym
            end
            
            pruned[new_key] = value
          end
        else
          pruned[key] = value
        end
      }
      
      pruned
    else
      mapped.to_h
    end
  else
    # Getting here means it was array-like, so it's already fine
    mapped
  end
end

.map_values(enumerable) {|key, value| ... } ⇒ Hash

Maps an enumerable object to a new hash with the same keys and values obtained by calling ‘block` with the current key and value.

If ‘enumerable` *does not* respond to `#to_pairs` then it’s treated as a hash where the elements iterated by ‘#each` are it’s keys and all it’s values are ‘nil`.

In this way, map_values handles Hash, Array, Set, OpenStruct, and probably pretty much anything else reasonable you may throw at it.

Parameters:

  • enumerable (#each_pair, #each)

Yield Parameters:

  • key (Object)

    The key that will be used for whatever value the block returns in the new hash.

  • value (nil, Object)

    If ‘enumerable` responds to `#each_pair`, the second parameter it yielded along with `key`. Otherwise `nil`.

Yield Returns:

  • (Object)

    Value for the new hash.

Returns:

  • (Hash)

Raises:

  • (TypeError)

    If ‘enumerable` does not respond to `#each_pair` or `#each`.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/nrser/enumerable.rb', line 39

def map_values enumerable, &block
  result = {}
  
  if enumerable.respond_to? :each_pair
    enumerable.each_pair { |key, value|
      result[key] = block.call key, value
    }
  elsif enumerable.respond_to? :each
    enumerable.each { |key| 
      result[key] = block.call key, nil
    }
  else
    raise TypeError.new NRSER.squish "      First argument must respond to #each_pair or #each\n      (found \#{ enumerable.inspect })\n    END\n  end\n  \n  result\nend\n"

.merge_by(current, *updates, &getter) ⇒ return_type

TODO:

Document merge_by method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



18
19
20
21
22
# File 'lib/nrser/merge_by.rb', line 18

def merge_by current, *updates, &getter
  updates.reduce( to_h_by current, &getter ) { |result, update|
    deep_merge! result, to_h_by(update, &getter)
  }.values
end

.message(*args, &block) ⇒ NRSER::Message

Creates a new Message from the array.

Examples:


message = NRSER::Op.message( :fetch, :x )
message.send_to x: 'ex', y: 'why?'
# => 'ex'

Returns:



34
35
36
37
38
39
40
# File 'lib/nrser/proc.rb', line 34

def self.message *args, &block
  if args.length == 1 && args[0].is_a?( Message )
    args[0]
  else
    Message.new *args, &block
  end
end

.only(enum, default: nil) ⇒ Object

Return the only entry if the enumerable has ‘#count` one. Otherwise, return `default` (which defaults to `nil`).

Parameters:

  • enum (Enumerable)

    Enumerable in question.

  • default: (Object) (defaults to: nil)

    Value to return if ‘enum` does not have only one entry.

Returns:

  • (Object)

    The only entry in ‘enum` if it has only one, else `default`.



122
123
124
125
126
127
128
# File 'lib/nrser/enumerable.rb', line 122

def only enum, default: nil
  if enum.count == 1
    enum.first
  else
    default
  end
end

.only!(enum) ⇒ return_type

TODO:

Document only method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



139
140
141
142
143
144
145
146
147
# File 'lib/nrser/enumerable.rb', line 139

def only! enum
  unless enum.count == 1
    raise TypeError.new squish <<-END
      Expected enumerable #{ enum.inspect } to have exactly one entry.
    END
  end
  
  enum.first
end

.private_sender(symbol, *args, &block) ⇒ Proc

Create a Proc that sends the arguments to a receiver via ‘#send`, forcing access to private and protected methods.

Equivalent to

message( symbol, *args, &block ).to_proc publicly: false

Pretty much here for completeness’ sake.

Examples:


sender( :fetch, :x ).call x: 'ex'
# => 'ex'

Returns:

  • (Proc)


84
85
86
# File 'lib/nrser/proc.rb', line 84

def self.private_sender symbol, *args, &block
  message( symbol, *args, &block ).to_proc publicly: false
end

.public_sender(symbol, *args, &block) ⇒ Proc

Create a Proc that sends the arguments to a receiver via ‘#public_send`.

Equivalent to

message( symbol, *args, &block ).to_proc

Pretty much here for completeness’ sake.

Examples:


sender( :fetch, :x ).call x: 'ex'
# => 'ex'

Returns:

  • (Proc)


60
61
62
# File 'lib/nrser/proc.rb', line 60

def self.public_sender symbol, *args, &block
  message( symbol, *args, &block ).to_proc
end

.rest(array) ⇒ return_type

Functional implementation of “rest” for arrays. Used when refining ‘#rest` into Array.

Parameters:

  • array (Array)

Returns:

  • (return_type)

    New array consisting of all elements after the first.



11
12
13
# File 'lib/nrser/array.rb', line 11

def self.rest array
  array[1..-1]
end

.retriever(key) ⇒ Proc

Return a Proc that accepts a single argument that must respond to ‘#[]` and retrieves `key` from it.

Parameters:

  • key (String | Symbol | Integer)

    Key (or index) to retrieve.

Returns:

  • (Proc)


129
130
131
# File 'lib/nrser/proc.rb', line 129

def self.retriever key
  ->( indexed ) { indexed[key] }
end

.slice_keys(hash, *keys) ⇒ Object

Lifted from ActiveSupport.



11
12
13
14
15
16
17
18
19
20
# File 'lib/nrser/hash/slice_keys.rb', line 11

def self.slice_keys hash, *keys
  # We're not using this, but, whatever, leave it in...
  if hash.respond_to?(:convert_key, true)
    keys.map! { |key| hash.send :convert_key, key }
  end
  
  keys.each_with_object(hash.class.new) { |k, new_hash|
    new_hash[k] = hash[k] if hash.has_key?(k)
  }
end

.slice_keys!(hash, *keys) ⇒ Object

Meant to be a drop-in replacement for the ActiveSupport version, though I’ve changed the implementation a bit… because honestly I didn’t understand why they were doing it the way they do :/



30
31
32
33
34
35
36
37
38
39
# File 'lib/nrser/hash/slice_keys.rb', line 30

def self.slice_keys! hash, *keys
  # We're not using this, but, whatever, leave it in...
  if hash.respond_to?(:convert_key, true)
    keys.map! { |key| hash.send :convert_key, key }
  end
  
  slice_keys( hash, *keys ).tap { |slice|
    except_keys! hash, *keys
  }
end

.smart_ellipsis(string, max, omission: UNICODE_ELLIPSIS, split: ', ') ⇒ String

**EXPERIMENTAL!**

Try to do “smart” job adding ellipsis to the middle of strings by splitting them by a separator ‘split` - that defaults to `, ` - then building the result up by bouncing back and forth between tokens at the beginning and end of the string until we reach the `max` length limit.

Intended to be used with possibly long single-line strings like ‘#inspect` returns for complex objects, where tokens are commonly separated by `, `, and producing a reasonably nice result that will fit in a reasonable amount of space, like `rspec` output (which was the motivation).

If ‘string` is already less than `max` then it is just returned.

If ‘string` doesn’t contain ‘split` or just the first and last tokens alone would push the result over `max` then falls back to ellipsis.

If ‘max` is too small it’s going to fall back nearly always… around ‘64` has seemed like a decent place to start from screwing around on the REPL a bit.

Parameters:

  • string (String)

    Source string.

  • max (Fixnum)

    Max length to allow for the output string. Result will usually be less than this unless the fallback to ellipsis kicks in.

  • omission: (String) (defaults to: UNICODE_ELLIPSIS)

    The string to stick in the middle where original contents were removed. Defaults to the unicode ellipsis since I’m targeting the CLI at the moment and it saves precious characters.

  • split: (String) (defaults to: ', ')

    The string to tokenize the ‘string` parameter by. If you pass a Regexp here it might work, it might loop out, maybe.

Returns:

  • (String)

    String of at most ‘max` length with the middle chopped out if needed to do so.



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/nrser/string.rb', line 196

def smart_ellipsis string, max, omission: UNICODE_ELLIPSIS, split: ', '
  return string unless string.length > max
  
  unless string.include? split
    return ellipsis string, max, omission: omission
  end
  
  tokens = string.split split
  
  char_budget = max - omission.length
  start = tokens[0] + split
  finish = tokens[tokens.length - 1]
  
  if start.length + finish.length > char_budget
    return ellipsis string, max, omission: omission
  end
  
  next_start_index = 1
  next_finish_index = tokens.length - 2
  next_index_is = :start
  next_index = next_start_index
  
  while (
    start.length + 
    finish.length +
    tokens[next_index].length +
    split.length
  ) <= char_budget do
    if next_index_is == :start
      start += tokens[next_index] + split
      next_start_index += 1
      next_index = next_finish_index
      next_index_is = :finish
    else # == :finish
      finish = tokens[next_index] + split + finish
      next_finish_index -= 1
      next_index = next_start_index
      next_index_is = :start
    end
  end
  
  start + omission + finish
  
end

.squish(str) ⇒ Object Also known as: unblock

turn a multi-line string into a single line, collapsing whitespace to a single space.

same as ActiveSupport’s String.squish, adapted from there.



24
25
26
# File 'lib/nrser/string.rb', line 24

def squish str
  str.gsub(/[[:space:]]+/, ' ').strip
end

.stringify_keys(hash) ⇒ Hash<String, *>

Returns a new hash with all keys transformed to strings by calling ‘#to_s` on them.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

Returns:

  • (Hash<String, *>)


31
32
33
# File 'lib/nrser/hash/stringify_keys.rb', line 31

def self.stringify_keys hash
  transform_keys hash, &:to_s
end

.stringify_keys!(hash) ⇒ Hash<String, *>

Converts all keys into strings by calling ‘#to_s` on them. **Mutates the hash.**

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

Returns:

  • (Hash<String, *>)


15
16
17
# File 'lib/nrser/hash/stringify_keys.rb', line 15

def self.stringify_keys! hash
  transform_keys! hash, &:to_s
end

.symbolize_keys(hash) ⇒ Hash

Returns a new hash with all keys that respond to ‘#to_sym` converted to symbols.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

Returns:

  • (Hash)

See Also:



34
35
36
37
# File 'lib/nrser/hash/symbolize_keys.rb', line 34

def self.symbolize_keys hash
  # File 'lib/active_support/core_ext/hash/keys.rb', line 54
  transform_keys(hash) { |key| key.to_sym rescue key }
end

.symbolize_keys!(hash) ⇒ Hash

Mutates ‘hash` by converting all keys that respond to `#to_sym` to symbols.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

Returns:

  • (Hash)

See Also:



16
17
18
# File 'lib/nrser/hash/symbolize_keys.rb', line 16

def self.symbolize_keys! hash
  transform_keys!(hash) { |key| key.to_sym rescue key }
end

.to_h_by(enum, &block) ⇒ return_type

TODO:

Document to_h_by method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/nrser/enumerable.rb', line 159

def to_h_by enum, &block
  {}.tap { |result|
    enum.each { |element|
      key = block.call element
      
      if result.key? key
        raise NRSER::ConflictError.new NRSER.dedent "          Key \#{ key.inspect } is already in results with value:\n          \n          \#{ result[key].pretty_inspect }\n        END\n      end\n      \n      result[key] = element\n    }\n  }\nend\n"

.to_open_struct(hash, freeze: false) ⇒ OpenStruct

Deeply convert a Hash to an OpenStruct.

Parameters:

  • hash (Hash)

Returns:

  • (OpenStruct)

Raises:

  • (TypeError)

    If ‘hash` is not a Hash.



17
18
19
20
21
22
23
24
# File 'lib/nrser/open_struct.rb', line 17

def to_open_struct hash, freeze: false
  unless hash.is_a? Hash
    raise TypeError,
          "Argument must be hash (found #{ hash.inspect })"
  end
  
  _to_open_struct hash, freeze: freeze
end

.transform(tree, source) ⇒ return_type

TODO:

Document transform method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



21
22
23
24
25
26
27
28
29
# File 'lib/nrser/tree/transform.rb', line 21

def self.transform tree, source
  map_tree( tree, prune: true ) { |value|
    if value.is_a? Proc
      value.call source
    else
      value
    end
  }
end

.transform_keys(hash, &block) ⇒ Hash

Returns a new hash with each key transformed by the provided block.

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

Returns:

  • (Hash)

    New hash with transformed keys.

See Also:



33
34
35
36
37
38
39
40
# File 'lib/nrser/hash/transform_keys.rb', line 33

def self.transform_keys hash, &block
  # File 'lib/active_support/core_ext/hash/keys.rb', line 12
  result = {}
  hash.each_key do |key|
    result[yield(key)] = hash[key]
  end
  result
end

.transform_keys!(hash) ⇒ Hash

Lifted from ActiveSupport.

Parameters:

  • hash (Hash)

    Hash to mutate keys.

Returns:

  • (Hash)

    The mutated hash.

See Also:



13
14
15
16
17
18
19
# File 'lib/nrser/hash/transform_keys.rb', line 13

def self.transform_keys! hash
  # File 'lib/active_support/core_ext/hash/keys.rb', line 23
  hash.keys.each do |key|
    hash[yield(key)] = hash.delete(key)
  end
  hash
end

.transformer(&block) ⇒ return_type

TODO:

Document transformer method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



61
62
63
64
65
66
67
68
69
# File 'lib/nrser/tree/transform.rb', line 61

def self.transformer &block
  map_tree( block.call SendSerializer.new ) { |value|
    if value.is_a? SendSerializer
      value.to_proc
    else
      value
    end
  }
end

.truncate(str, truncate_at, options = {}) ⇒ Object

Truncates a given text after a given length if text is longer than length:

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

Pass a string or regexp :separator to truncate text at a natural break:

'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."

The last characters will be replaced with the :omission string (defaults to “…”) for a total length not exceeding length:

'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"

adapted from

<github.com/rails/rails/blob/7847a19f476fb9bee287681586d872ea43785e53/activesupport/lib/active_support/core_ext/string/filters.rb#L46>



109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/nrser/string.rb', line 109

def truncate(str, truncate_at, options = {})
  return str.dup unless str.length > truncate_at

  omission = options[:omission] || '...'
  length_with_room_for_omission = truncate_at - omission.length
  stop = \
    if options[:separator]
      str.rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
    else
      length_with_room_for_omission
    end

  "#{str[0, stop]}#{omission}"
end

.truthy?(object) ⇒ Boolean

Evaluate an object (that probably came from outside Ruby, like an environment variable) to see if it’s meant to represent true or false.

Parameters:

  • object (Nil, String)

    Value to test.

Returns:

  • (Boolean)

    ‘true` if the object is “truthy”.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/nrser/object/truthy.rb', line 34

def self.truthy? object
  case object
  when nil
    false
    
  when String
    downcased = object.downcase
    
    if TRUTHY_STRINGS.include? downcased
      true
    elsif FALSY_STRINGS.include? downcased
      false
    else
      raise ArgumentError,
            "String #{ object.inspect } not recognized as true or false."
    end
    
  when TrueClass, FalseClass
    object
    
  else
    raise TypeError,
          "Can't evaluate truthiness of #{ object.inspect }"
  end
end

.whitespace?(string) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/nrser/string.rb', line 11

def self.whitespace? string
  string =~ WHITESPACE_RE
end

.with_indent_tagged(text, marker: INDENT_TAG_MARKER, separator: INDENT_TAG_SEPARATOR, &interpolate_block) ⇒ String

Indent tag a some text via indent_tag, call the block with it, then pass the result through indent_untag and return that.

Parameters:

  • marker: (String) (defaults to: INDENT_TAG_MARKER)

    Special string to mark the start of tagged lines. If interpolated text lines start with this string you’re going to have a bad time.

  • separator: (String) (defaults to: INDENT_TAG_SEPARATOR)

    Must be the separator used to tag the text.

Returns:

  • (String)

    Final text with interpolation and indent correction.



197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/nrser/text/indentation.rb', line 197

def self.with_indent_tagged text,
                            marker: INDENT_TAG_MARKER,
                            separator: INDENT_TAG_SEPARATOR,
                            &interpolate_block
  indent_untag(
    interpolate_block.call(
      indent_tag text, marker: marker, separator: separator
    ),
    marker: marker,
    separator: separator,
  )
end

.word_wrap(text, line_width: 80, break_sequence: "\n") ⇒ String

Split text at whitespace to fit in line length. Lifted from Rails’ ActionView.

Parameters:

  • text (String)

    Text to word wrap.

  • line_width: (Fixnum) (defaults to: 80)

    Line with in number of character to wrap at.

  • break_sequence: (String) (defaults to: "\n")

    String to join lines with.

Returns:

  • (String)

    @todo Document return value.

See Also:



22
23
24
25
26
# File 'lib/nrser/text/word_wrap.rb', line 22

def self.word_wrap text, line_width: 80, break_sequence: "\n"
  text.split("\n").collect! do |line|
    line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").strip : line
  end * break_sequence
end