module OpenString::ClassMethods

Methods meant to be members of the String class need to go in here. The machinery here is a little odd: since the randomize declaration isn’t prefaced with a self, it doesn’t look static. Once String is set to +extend OpenInteger::ClassMethods+, this is treated like a static String method.

If this inner module wasn’t created and, instead, String was set to +include OpenString+, consumers would need to call static methods via OpenString like so: +OpenString.randomize(10, CharacterSets.all)+.

Examples

↑ top

Public Instance Methods

randomize(length, *charsets) click to toggle source
# File lib/open_string.rb, line 40
def randomize(length, *charsets)
  raise(ArgumentError,
        'Do not pass nil for length.') if length.nil?
  raise(ArgumentError,
        'Length must be a non-zero positive integer.') if length < 1
  raise(ArgumentError,
        'Specify a character set.') if charsets.empty?

  Array.new(length) { charsets.flatten.sample }.join
end