How can I add an alias to Ruby 1.9's Enocding.aliases?

342 Views Asked by At

Wanted to add an alias for one of the charsets that PayPal may use for its IPN (Instant Payment Notification).

This is silently ignored:

Encoding.aliases["x-mac-greek"] = "macGreek"

This doesn't work, either:

Encoding.aliases.update("x-mac-greek" => "macGreek")

Any other suggestions?

3

There are 3 best solutions below

2
On BEST ANSWER

I don't think this is possible. If you look at the source for the aliases method you can see that it creates a new hash each time it's called, with the aliases copied into from the internal representation.

From what I can see it doesn't look like there's any way to modify this internal data from a Ruby program.

Perhaps you just need to check the string you get from PayPal before trying to use it as an encoding.

2
On

You can force a new definition of Encoding.aliases. It may or may be not useful for your purposes:I do not know if it will be picked up by other classes; it should but it may not.

Encoding.instance_eval <<__END
    alias :orig_aliases :aliases
    def aliases
        orig_aliases.update("x-mac-greek" => "macGreek")
    end
__END
0
On

A following C extension will work:

#include <ruby.h>

extern VALUE rb_cEncoding;
int rb_encdb_alias(const char *alias, const char *orig);

/*
 * Add alias to an existing encoding
 *
 * Encoding.add_alias('hebrew', 'Windows-1255') -> 'hebrew'
 *
 */
VALUE rb_add_alias(VALUE self, VALUE alias,  VALUE orig)
{
    if (rb_encdb_alias(RSTRING_PTR(alias), RSTRING_PTR(orig)) == -1) {
        return Qnil;
    } else {
        return alias;
    }
}

void Init_enc_alias() {
    rb_define_singleton_method(rb_cEncoding, "add_alias", rb_add_alias, 2);
}