mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-26 01:33:22 +00:00
Create UrlGenerator service
This commit is contained in:
16
app/services/url_generator.rb
Normal file
16
app/services/url_generator.rb
Normal file
@@ -0,0 +1,16 @@
|
||||
# frozen_string_literal: false
|
||||
|
||||
# Converts strings for use as parts of a URL. The input can contain non-roman/non-UTF8 characters
|
||||
# and the output will still be valid (including some transliteration). Examples:
|
||||
#
|
||||
# "Top Cat!" -> "top-cat"
|
||||
# "Père Noël" -> "pere-noel"
|
||||
# "你好" -> "ni-hao"
|
||||
|
||||
require "stringex/unidecoder"
|
||||
|
||||
class UrlGenerator
|
||||
def self.to_url(string)
|
||||
Stringex::Unidecoder.decode(string.to_s).parameterize
|
||||
end
|
||||
end
|
||||
21
spec/services/url_generator_spec.rb
Normal file
21
spec/services/url_generator_spec.rb
Normal file
@@ -0,0 +1,21 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'spec_helper'
|
||||
|
||||
describe UrlGenerator do
|
||||
subject { UrlGenerator }
|
||||
|
||||
describe "#to_url" do
|
||||
it "converts to url-safe strings and removes unusable characters" do
|
||||
expect(subject.to_url("Top Cat!?")).to eq "top-cat"
|
||||
end
|
||||
|
||||
it "handles unusual characters like accents and umlauts" do
|
||||
expect(subject.to_url("Père Noël")).to eq "pere-noel"
|
||||
end
|
||||
|
||||
it "handles transliteration of Chinese characters" do
|
||||
expect(subject.to_url("你好")).to eq "ni-hao"
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user