challenge: correctly handling Accept-Language HTTP header

K

khaines

I've been pondering the best way of writing a piece of code that will,
when given a list of language options, select the one that best fullfills
what is being requested in an Accept-Language header.

i.e.

If one has a list of en, en-gb and es, and one gets an Accept-Language
header like this:

es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3

the code would return the 'es' as the best matching language option.

Is there some already written Ruby code hiding in a project somewhere to
do this? Is there some piece of C library somewhere that I could just
write an extension for to do it? Can someone offer up a fast Ruby
implementation to handle Accept-Language decisions?

I've hacked out an almost right approach, but I'm not happy with it.


Thanks,

Kirk Haines
 
D

David Vallner

--------------enig13035FB3AA5E2804F508CD71
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

If one has a list of en, en-gb and es, and one gets an Accept-Language
header like this:
=20
es-mx,es;q=3D0.8,en-us;q=3D0.5,en;q=3D0.3
=20
the code would return the 'es' as the best matching language option.
=20

I have some doubts you'll ever see that sort of header in the wild.

Besides, parsing that one is hardly something that needs a C library.

Here's an almost-one-liner, if you're willing to forgive the each block
being three statements and remove all whitespace (it actually parses...)

"es-mx,es;q=3D0.8,en-us;q=3D0.5,en;q=3D0.3".split(",").map { | i |
i.split(";")
}.each { | i |
i[1] =3D~ /q=3D(\d+\.\d+)/;
i[1] =3D $1 && $1.to_f || 1.0
}.sort_by{ | i |
i[1]
}.reverse[0][0]

=3D> "es-mx"

(The quality value for es-mx defaults to 1, es is only 0.8)

David Vallner
(That's by far the ugliest code I've written in a year.)


--------------enig13035FB3AA5E2804F508CD71
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
Content-Disposition: attachment; filename="signature.asc"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (MingW32)

iD8DBQFFOB2jy6MhrS8astoRAtLvAJ9Y2622jFm67RtzAwAxNZNhjsc1WwCcC9vx
g7u0k6RYdoZ8zeIktQEBBKo=
=DJeg
-----END PGP SIGNATURE-----

--------------enig13035FB3AA5E2804F508CD71--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top