This commit is contained in:
Matt Jankowski 2024-10-17 10:09:33 +00:00 committed by GitHub
commit 766354fdc7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 87 additions and 12 deletions

View File

@ -87,18 +87,11 @@ class DomainBlock < ApplicationRecord
end
def public_domain
return domain unless obfuscate?
length = domain.size
visible_ratio = length / 4
domain.chars.map.with_index do |chr, i|
if i > visible_ratio && i < length - visible_ratio && chr != '.'
'*'
else
chr
end
end.join
if obfuscate?
ObfuscatedDomainPresenter.new(domain).to_s
else
domain
end
end
def domain_digest

View File

@ -0,0 +1,49 @@
# frozen_string_literal: true
class ObfuscatedDomainPresenter
attr_reader :domain, :placeholder
PRESERVED_CHARACTERS = %w(.).freeze
VISIBLE_WINDOW_EDGE = 4
def initialize(domain, placeholder: '*')
@domain = domain
@placeholder = placeholder
end
def to_s
domain_characters
.with_index { |character, index| solution(character, index) }
.join
end
private
def solution(character, index)
if midstream?(index) && PRESERVED_CHARACTERS.exclude?(character)
placeholder
else
character
end
end
def midstream?(index)
index > visible_ratio && index < ending_boundary
end
def domain_characters
domain.chars.map
end
def length
@length ||= domain.size
end
def visible_ratio
@visible_ratio ||= length / VISIBLE_WINDOW_EDGE
end
def ending_boundary
@ending_boundary ||= length - visible_ratio
end
end

View File

@ -0,0 +1,33 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ObfuscatedDomainPresenter do
describe '#to_s' do
subject { described_class.new(domain).to_s }
context 'with a short domain' do
let(:domain) { 'abc.com' }
it { is_expected.to eq('ab*.**m') }
end
context 'with a long domain' do
let(:domain) { 'alphabet.soup.is.good.for.breakfast.and.lunch.and.dinner.org' }
it { is_expected.to eq('alphabet.soup.is.****.***.*********.***.*****.and.dinner.org') }
end
context 'with a domain from the federalized multiverse' do
let(:domain) { 'mastodon.social' }
it { is_expected.to eq('mast****.***ial') }
end
context 'with a series of dots' do
let(:domain) { '.....' }
it { is_expected.to eq('.....') }
end
end
end