2012-01-24 13 views

回答

1

我不認爲這是可能的。如果您查看the source for the aliases method,您可以看到它每次調用時都會創建一個新的散列,並將別名從內部表示中複製進來。

從我可以看到它看起來沒有任何方式可以從Ruby程序修改這些內部數據。

也許你只是需要檢查你從PayPal獲得的字符串,然後再嘗試使用它作爲編碼。

+0

感謝您的見解。我想要實現的是不可能的,這很清楚。 –

+0

這些別名在Ruby中如何加載?有沒有辦法掛鉤到該進程添加更多的別名? –

0

您可以強制新定義Encoding.aliases。它可能會或可能不會對您的目的有用:我不知道它是否會被其他類拾取;它應該,但它可能不會。

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

這隻會影響從'aliases'返回的數組。 Ruby使用的內部數據結構將保持不變。例如,它不會允許你執行''Foo「.force_encoding(」x-mac-greek「)' - 你會得到'ArgumentError:未知的編碼名稱 - x-mac-greek',就像你不這樣做。 – matt

+0

如果'force_encoding'使用了'Encoding.aliases'的返回值,它就會工作得很好。但對於這樣一種常用的方法來說,採用快捷方式並讀取用於生成原始「Encoding.aliases」哈希的相同內部數據是有意義的。 – gioele

1

阿繼C擴展將工作:

#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); 
} 
+0

這對我有效,謝謝 –