module ParaDice::Utility
provides utility methods used by other parts of ParaDice
.
Public Class Methods
from_summary(summary)
click to toggle source
from_summary
creates an array and populates with a number of each key
equal to the value for that key
@example Make an array from a Summary Hash
summary = {foo: 3, bar: 1, baz: 2} ParaDice::Utility.from_summary(summary) # => [:foo,:foo,:foo,:bar,:baz,:baz]
@param [Hash<Object,Fixnum>] summary a hash to inflate a summary into an array @return [Array<Object>]
# File lib/para_dice/utility.rb, line 48 def self.from_summary(summary) summary.each_pair.map { |e, c| Array.new(c) { e } }.flatten end
module_from(name, namespace = nil)
click to toggle source
Generate a Class or Module from a representation for the class. @example Get a module from
ParaDice::Utility.module_from(String) # => String ParaDice::Utility.module_from('string') # => String ParaDice::Utility.module_from('String') # => String ParaDice::Utility.module_from('STRING') # => String ParaDice::Utility.module_from(:string) # => String ParaDice::Utility.module_from(:String) # => String ParaDice::Utility.module_from('paradise/utility') # => Paradise::Utility ParaDice::Utility.module_from('paradise__utility') # => Paradise::Utility ParaDice::Utility.module_from('Paradise::Utility') # => Paradise::Utility ParaDice::Utility.module_from('Utility', 'ParaDice') # => Paradise::Utility ParaDice::Utility.module_from('Utility', ParaDice) # => Paradise::Utility
@param [Class,Module,#to_s] name @param [Class, Module, to_s] namespace @return [false] if no name is found at top level or namespace @return [Class,Module] the class or module represented by name
and optionally in namespace
# File lib/para_dice/utility.rb, line 24 def self.module_from(name, namespace = nil) return name if name.is_a? Module return false if name.empty? self.module_from_top(name) || self.module_from_namespace(name, namespace) end
to_summary(arr)
click to toggle source
to_summary
creates a hash and populates it with uniq elements of the
array, and the count of how many there are
@example Make a summary from array
arr = [2,3,1,2,3,2,3] ParaDice::Utility.to_summary(arr) # => { 1 => 1, 2 => 3, 3 => 3}
@param [Array] arr a list to summarize @return [Hash]
# File lib/para_dice/utility.rb, line 37 def self.to_summary(arr) arr.reduce(Hash.new(0)) { |h, e| h[e] += 1; h } end
Private Class Methods
module_from_namespace(raw_name, namespace)
click to toggle source
# File lib/para_dice/utility.rb, line 60 def self.module_from_namespace(raw_name, namespace) return false unless namespace name = raw_name.to_s.modulize return false unless namespace.const_defined?(name) namespace.const_get(name) end
module_from_top(raw_name)
click to toggle source
# File lib/para_dice/utility.rb, line 53 def self.module_from_top(raw_name) name = raw_name.to_s.modulize return false if name.empty? return false unless Kernel.const_defined?(name) Kernel.const_get(name) end