Ecco una gemma che mantiene numerico, non richiede migrazioni di database, e nessun cambiamento di routing: https://github.com/namick/obfuscate_id
ho trovato che questo gioiello non funziona in concerto con alcune altre gemme, in particolare paper_trail. Ciò è dovuto al modo in cui sostituisce il metodo find
e paper_trail fa sì che find
venga chiamato con l'ID record effettivo.
Quindi ho usato la funzionalità "scatter_swap" della gemma, ma non il resto. Ecco il modello:
require 'obfuscate_id/scatter_swap'
class Page < ActiveRecord::Base
# This is a random number that, if changed, will invalidate all existing URLs. Don't change it!
@@obfuscate_spin = # random number here, which is essentially the encryption key
##
# Generate URL parameter to be used in the URL as the "id"
def to_param
# Use the obfuscate_id gem's class to "spin" the id into something obfuscated
spun_id = ScatterSwap.hash(self.id, @@obfuscate_spin)
# Throw any additional attributes in here that are to be included in the URL.
"#{spun_id} #{name}".parameterize
end
def self.find_by_slug!(slug)
spun_id = slug[/^[0-9]+/]
begin
find_by_id! ScatterSwap.reverse_hash(spun_id, @@obfuscate_spin)
rescue ActiveRecord::RecordNotFound => e
raise ActiveRecord::RecordNotFound, "Couldn't find matching Page."
end
end
end
E nel controller:
class PagesController < InheritedResources::Base
# Find the page using its URL slug
before_filter :find_page, except: [:index, :create, :new]
def find_page
@page = Page.find_by_slug! params[:id]
# If the URL doesn't match exactly, and this is a GET.
# We'll redirect to the new, correct URL, but if this is a non-GET, let's let them finish their request instead.
if params[:id] != @page.to_param && request.get?
redirect_to url_for({ id: @page.to_param }), status: 301
end
end
end
In alternativa il reindirizzamento che avviene lì, si può semplicemente inserire un URL canonico nella pagina. Il reindirizzamento ha il bug di ignorare qualsiasi parametro di query nell'URL. Questo non era un problema per il mio progetto, perché non ne avevo. Ma un URL canonico sarebbe meglio.
fonte
2013-02-10 02:59:03
Questo è fantastico :) C'è un modo per eliminare l'extra "==" alla fine della stringa crittografata? – Cyrus
Questo fa parte della crittografia Base64, quindi è necessario decrittografarlo. Puoi rimuoverlo nel metodo 'encrypt' e aggiungerlo di nuovo nel metodo' decrypt', ma potrebbe essere più incline all'errore (dato che non sono sicuro che Base64 * always * includa '==' alla fine della stringa). – siannopollo
Base64 esce con '=' se il numero di bit codificati non corrisponde esattamente. Ci saranno zero, uno o due di essi a seconda della lunghezza dell'input. – tadman