Last active
December 14, 2015 04:09
-
-
Save keithrbennett/5026518 to your computer and use it in GitHub Desktop.
Example JRuby program to display the JVM's available locales and their number, currency, and date formats. Change the format constants to see more kinds of formatting (e.g. DateFormat::LONG/SHORT). - Keith R. Bennett, @keithrbennett
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example JRuby program to display the JVM's available locales | |
# and their number, currency, and date formats. | |
# | |
# Keith R. Bennett, @keithrbennett | |
require 'java' | |
java_import 'java.util.Locale' | |
java_import 'java.text.DateFormat' | |
java_import 'java.text.NumberFormat' | |
class NumberFormat | |
java_alias :format_double, :format, [Java::double] | |
end | |
class LocaleDisplayer | |
class LocaleData | |
attr_reader :java_locale, :number_formatter, :currency_formatter, :date_time_formatter | |
def initialize(java_locale) | |
@java_locale = java_locale | |
setup_formatters | |
end | |
def setup_formatters | |
@date_time_formatter = java.text.DateFormat.java_send(:getDateTimeInstance, | |
[Java::int, Java::int, Locale], | |
DateFormat::MEDIUM, DateFormat::MEDIUM, java_locale) | |
@number_formatter = NumberFormat.java_send(:getInstance, [Locale], java_locale) | |
@currency_formatter = NumberFormat.java_send(:getCurrencyInstance, [Locale], java_locale) | |
end | |
def format_number(number) | |
number_formatter.format_double(number) | |
end | |
def format_currency(number) | |
currency_formatter.format_double(number) | |
end | |
def format_date(date) | |
date_time_formatter.format(date) | |
end | |
def display_name | |
java_locale.display_name | |
end | |
def code | |
java_locale.toString | |
end | |
end | |
def format_string | |
"%-12.12s %-20.20s %-30.30s %-17.17s %-17.17s\n" | |
end | |
def header_line | |
format_string % ['Code', 'Description', 'Date Format', 'Number Format', 'Currency Format'] | |
end | |
def data_line(locale_data) | |
format_string % [ | |
locale_data.code, | |
locale_data.display_name, | |
locale_data.format_date(java.util.Date.new), | |
locale_data.format_number(java.lang.Double.new(1234567.89)), | |
locale_data.format_currency(java.lang.Double.new(1234567.89)), | |
] | |
end | |
def all_locales | |
@all_locales ||= | |
Locale.available_locales.sort do |locale_1, locale_2| | |
locale_1.display_name <=> locale_2.display_name | |
end | |
end | |
def print_all(out = STDOUT) | |
out << header_line << "\n" | |
all_locales.each { |locale| out << data_line(LocaleData.new(locale)) } | |
end | |
end | |
LocaleDisplayer.new.print_all |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment