class HumanizedId::Humanizer

Constants

SOURCE_CHARSET

Public Class Methods

new(id:, min_length: nil, prefix: '') click to toggle source
# File lib/humanized_id/humanizer.rb, line 6
def initialize(id:, min_length: nil, prefix: '')
  @id               = id
  @min_length       = min_length
  @prefix           = prefix.to_s
  @target_charset   = CHARSET.join
  @source_charset   = SOURCE_CHARSET.join
end

Public Instance Methods

generate_humanized_id() click to toggle source
# File lib/humanized_id/humanizer.rb, line 14
def generate_humanized_id
  new_id = resize convert_to_target_charset convert_to_target_base(@id)
  "#{@prefix}#{new_id}"
end

Private Instance Methods

convert_to_target_base(id) click to toggle source
# File lib/humanized_id/humanizer.rb, line 21
def convert_to_target_base(id)
  fail Error, 'id is not an integer' unless id.is_a? Integer
  id.to_s(@target_charset.length)
end
convert_to_target_charset(id) click to toggle source
# File lib/humanized_id/humanizer.rb, line 26
def convert_to_target_charset(id)
  source_charset_subset = @source_charset.slice(0, @target_charset.length)
  id.tr(source_charset_subset, @target_charset)
end
resize(id) click to toggle source
# File lib/humanized_id/humanizer.rb, line 31
def resize(id)
  return id if @min_length.nil? || @min_length <= id.length
  padding = @target_charset[0] * (@min_length - id.length)
  "#{padding}#{id}"
end