Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save secretpray/1af99d8c382f33ccba126fbc28056aaa to your computer and use it in GitHub Desktop.
Save secretpray/1af99d8c382f33ccba126fbc28056aaa to your computer and use it in GitHub Desktop.
Add masked_email and display_name to Rails User model
  def display_name
    Rails.cache.fetch("profile_#{id}_display_name", expires_in: 1.month) do
      nickname_from_email
    end
  end

  def masked_email
    Rails.cache.fetch("profile_#{id}_masked_email", expires_in: 1.month) do
      return nil unless email.present?

      parts = email.split('@')
      "#{masked_username(parts.first)}@#{parts.last}"
      # username = parts.first
      # domain = parts.last
      # "#{masked_username(username)}@#{masked_domain(domain)}"
    end
  end

  private

  def nickname_from_email
    name_part = email.split('@').first
    return name_part if ['.', '_', '-'].include?(name_part[1])

    name_part.humanize
  end

  def masked_username(username)
    if username.length < 4
      "#{username[0]}#{'.' * (username.length - 1)}"
    else
      "#{username[0]}#{'.' * (username.length - 2)}#{username[-1]}"
    end
  end

  # def masked_domain(domain)
  #   "#{domain[0]}#{'.' * (domain.length - 2)}#{domain[-1]}" if domain.length > 2
  # end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment