Skip to content

Instantly share code, notes, and snippets.

@nobu
Created November 6, 2009 07:31
Show Gist options
  • Save nobu/227796 to your computer and use it in GitHub Desktop.
Save nobu/227796 to your computer and use it in GitHub Desktop.
Locale module
$ ./ruby -rlocale -e 'p ENV.values_at(*%w[LC_ALL LC_TIME LANG]);
t = Time.now
puts t
Locale.all=""
puts t
Locale.time="C"
puts t'
[nil, nil, "ja_JP.UTF-8"]
Fri Nov 06 16:38:50 +0900 2009
金 11 06 16:38:50 +0900 2009
Fri Nov 06 16:38:50 +0900 2009
require 'mkmf'
extension_name = 'locale'
header = "locale.h"
dir_config(extension_name)
if have_header(header)
lc = %w[CTYPE NUMERIC TIME COLLATE MONETARY MESSAGES ALL]
lc = lc.delete_if {|n| !have_macro("LC_#{n}", header)}.
collect {|n| "def(#{n.downcase}, LC_#{n})"}.
join(" \t")
$defs << "-Dforeach_categories(def)=\"\t#{lc}\""
create_header
create_makefile(extension_name)
end
#include <locale.h>
#include "ruby.h"
static VALUE
rb_setlocale(int category, const char *locale)
{
char *r = setlocale(category, locale);
if (!r) rb_raise(rb_eRuntimeError, "setlocale");
return rb_str_new2(r);
}
static inline VALUE
locale_set(int category, VALUE locale)
{
return rb_setlocale(category, StringValueCStr(locale));
}
static inline VALUE
locale_get(int category)
{
return rb_setlocale(category, NULL);
}
#define funcs(n, c) \
static VALUE rb_getlocale_##n(VALUE self) {return locale_get(c);} \
static VALUE rb_setlocale_##n(VALUE self, VALUE val) {return locale_set(c, val);} \
/* end of funcs */
foreach_categories(funcs)
void
Init_locale(void)
{
VALUE locale = rb_define_module("Locale");
#define methods(n, c) \
rb_define_singleton_method(locale, #n, rb_getlocale_##n, 0); \
rb_define_singleton_method(locale, #n"=", rb_setlocale_##n, 1); \
/* end of methods */
foreach_categories(methods);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment