nested-delocalize 0.1.8

Sign up to get free protection for your applications and to get access to all the features.
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Clemens Kofler
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,117 @@
1
+ delocalize
2
+ ==========
3
+
4
+ delocalize provides localized date/time and number parsing functionality for Rails.
5
+
6
+ Installation
7
+ ============
8
+
9
+ You can use delocalize either as a gem (preferred) or as a Rails plugin.
10
+
11
+ To use the gem version, put the following gem requirement in your environment.rb:
12
+
13
+ config.gem "delocalize", :source => 'http://gemcutter.org'
14
+
15
+ To install it as a plugin, fire up your terminal, go to your Rails app and type:
16
+
17
+ $ ruby script/plugin install git://github.com/clemens/delocalize.git
18
+
19
+
20
+ What does it do? And how do I use it?
21
+ =====================================
22
+
23
+ Delocalize, just as the name suggest, does pretty much the opposite of localize.
24
+
25
+ In the grey past, ff you want your users to be able to input localized data, such as dates and numbers, you had to manually override attribute accessors:
26
+
27
+ def price=(price)
28
+ write_attribute(:price, price.gsub(',', '.'))
29
+ end
30
+
31
+ delocalize does this under the covers - all you need is your regular translation data (as YAML or Ruby file) where you need Rails' standard translations:
32
+
33
+ de:
34
+ number:
35
+ format:
36
+ separator: ','
37
+ delimiter: '.'
38
+ date:
39
+ input:
40
+ formats: [:default, :long, :short] # <- this and ...
41
+
42
+ formats:
43
+ default: "%d.%m.%Y"
44
+ short: "%e. %b"
45
+ long: "%e. %B %Y"
46
+ only_day: "%e"
47
+
48
+ day_names: [Sonntag, Montag, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag]
49
+ abbr_day_names: [So, Mo, Di, Mi, Do, Fr, Sa]
50
+ month_names: [~, Januar, Februar, März, April, Mai, Juni, Juli, August, September, Oktober, November, Dezember]
51
+ abbr_month_names: [~, Jan, Feb, Mär, Apr, Mai, Jun, Jul, Aug, Sep, Okt, Nov, Dez]
52
+ order: [ :day, :month, :year ]
53
+
54
+ time:
55
+ input:
56
+ formats: [:long, :medium, :short, :default, :time] # <- ... this are the only non-standard keys
57
+ formats:
58
+ default: "%A, %e. %B %Y, %H:%M Uhr"
59
+ short: "%e. %B, %H:%M Uhr"
60
+ long: "%A, %e. %B %Y, %H:%M Uhr"
61
+ time: "%H:%M"
62
+
63
+ am: "vormittags"
64
+ pm: "nachmittags"
65
+
66
+ For dates and times, you have to define input formats which are taken from the actual formats. The important thing here is to define input formats sorted by descending complexity - in other words: The format which contains the most (preferably non-numeric) information should be first in the list because it can produce the most reliable match. Exception: If you think there most complex format is not the one that most users will input, you can put the most-used in front so you save unnecessary iterations.
67
+
68
+ Careful with formats containing only numbers: It's very hard to produce reliable matches if you provide multiple strictly numeric formats!
69
+
70
+ delocalize then overrides to_input_field_tag in ActionView's InstanceTag so you can use localized text fields:
71
+
72
+ <% form_for @product do |f| %>
73
+ <%= f.text_field :name %>
74
+ <%= f.text_field :released_on %>
75
+ <%= f.text_field :price %>
76
+ <% end %>
77
+
78
+ In this example, a user can enter the release date and the price just like he's used to in his language, for example:
79
+
80
+ Name: "Couch"
81
+ Released on: "12. Oktober 2009"
82
+ Price: "2.999,90"
83
+
84
+ When saved, ActiveRecord automatically converts these to a regular Ruby date and number.
85
+
86
+ Edit forms then also show localized dates/numbers. By default, dates and times are localized using the format named :default in your locale file. So with the above locale file, dates would use "%d.%m.%Y" and times would use "%A, %e. %B %Y, %H:%M Uhr". Numbers are also formatted using your locale's thousands delimiter and decimal separator.
87
+
88
+ You can also customize the output using some options:
89
+
90
+ The price should always show two decimal digits and we don't need the delimiter:
91
+ <%= f.text_field :price, :precision => 2, :delimiter => '' %>
92
+
93
+ The released_on date should be shown in the :full format:
94
+ <%= f.text_field :released_on, :format => :full %>
95
+
96
+ Since I18n.localize supportes localizing strftime strings, we can also do this:
97
+ <%= f.text_field :released_on, :format => "%B %Y" %>
98
+
99
+ Note
100
+ ====
101
+
102
+ delocalize is most definitely not enterprise-ready! ;-)
103
+ Or as Yaroslav says: Contains small pieces. Not good for children of age 3 and less. Not enterprise-ready.
104
+
105
+ TODO
106
+ ====
107
+
108
+ * Improve test coverage
109
+ * Separate Ruby/Rails stuff to make it usable outside Rails
110
+ * Verify correct behavior with time zones
111
+ * Decide on other ActionView hacks (e.g. text_field_tag)
112
+ * Implement AM/PM support
113
+ * Cleanup, cleanup, cleanup ...
114
+
115
+ Copyright (c) 2009 Clemens Kofler <clemens@railway.at>
116
+ www.railway.at
117
+ Released under the MIT license
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ require 'tasks/distribution'
6
+ require 'tasks/documentation'
7
+ require 'tasks/testing'
8
+
9
+ desc 'Default: run unit tests.'
10
+ task :default => :test
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.8
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require 'delocalize'
@@ -0,0 +1,28 @@
1
+ module I18n
2
+ mattr_accessor :enable_delocalization
3
+ I18n.enable_delocalization = true
4
+
5
+ class << self
6
+ def delocalization_enabled?
7
+ !!I18n.enable_delocalization
8
+ end
9
+
10
+ def delocalization_disabled?
11
+ !delocalization_enabled?
12
+ end
13
+
14
+ def with_delocalization_disabled(&block)
15
+ old_value = I18n.enable_delocalization
16
+ I18n.enable_delocalization = false
17
+ yield
18
+ I18n.enable_delocalization = old_value
19
+ end
20
+
21
+ def with_delocalization_enabled(&block)
22
+ old_value = I18n.enable_delocalization
23
+ I18n.enable_delocalization = true
24
+ yield
25
+ I18n.enable_delocalization = old_value
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,68 @@
1
+ # TODO:
2
+ # * AM/PM calculation
3
+ # * proper documentation (comments)
4
+ module Delocalize
5
+ class LocalizedDateTimeParser
6
+ class << self
7
+ def parse(datetime, type)
8
+ return unless datetime
9
+ return datetime if datetime.respond_to?(:strftime) # already a Date/Time object -> no need to parse it
10
+
11
+ translate_month_and_day_names(datetime)
12
+ input_formats(type).each do |original_format|
13
+ next unless datetime =~ /^#{apply_regex(original_format)}$/
14
+
15
+ datetime = DateTime.strptime(datetime, original_format)
16
+ return Date == type ?
17
+ datetime.to_date :
18
+ Time.zone.local(datetime.year, datetime.mon, datetime.mday, datetime.hour, datetime.min, datetime.sec)
19
+ end
20
+ default_parse(datetime, type)
21
+ end
22
+
23
+ private
24
+ def default_parse(datetime, type)
25
+ return if datetime.blank?
26
+ begin
27
+ today = Date.current
28
+ parsed = Date._parse(datetime)
29
+ return if parsed.empty? # the datetime value is invalid
30
+ # set default year, month and day if not found
31
+ parsed.reverse_merge!(:year => today.year, :mon => today.mon, :mday => today.mday)
32
+ datetime = Time.zone.local(*parsed.values_at(:year, :mon, :mday, :hour, :min, :sec))
33
+ Date == type ? datetime.to_date : datetime
34
+ rescue
35
+ datetime
36
+ end
37
+ end
38
+
39
+ def translate_month_and_day_names(datetime)
40
+ translated = I18n.t([:month_names, :abbr_month_names, :day_names, :abbr_day_names], :scope => :date).flatten.compact
41
+ original = (Date::MONTHNAMES + Date::ABBR_MONTHNAMES + Date::DAYNAMES + Date::ABBR_DAYNAMES).compact
42
+ translated.each_with_index { |name, i| datetime.gsub!(name, original[i]) }
43
+ end
44
+
45
+ def input_formats(type)
46
+ # Date uses date formats, all others use time formats
47
+ type = type == Date ? :date : :time
48
+ (@input_formats ||= {})[type] ||= I18n.t(:"#{type}.formats").slice(*I18n.t(:"#{type}.input.formats")).values
49
+ end
50
+
51
+ def apply_regex(format)
52
+ # maybe add other options as well
53
+ format.gsub('%B', "(#{Date::MONTHNAMES.compact.join('|')})"). # long month name
54
+ gsub('%b', "(#{Date::ABBR_MONTHNAMES.compact.join('|')})"). # short month name
55
+ gsub('%m', "(\\d{2})"). # numeric month
56
+ gsub('%A', "(#{Date::DAYNAMES.join('|')})"). # full day name
57
+ gsub('%a', "(#{Date::ABBR_DAYNAMES.join('|')})"). # short day name
58
+ gsub('%Y', "(\\d{4})"). # long year
59
+ gsub('%y', "(\\d{2})"). # short year
60
+ gsub('%e', "(\\w?\\d{1,2})"). # short day
61
+ gsub('%d', "(\\d{2})"). # full day
62
+ gsub('%H', "(\\d{2})"). # hour (24)
63
+ gsub('%M', "(\\d{2})"). # minute
64
+ gsub('%S', "(\\d{2})") # second
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,17 @@
1
+ # TODO:
2
+ # * proper documentation (comments)
3
+ module Delocalize
4
+ class LocalizedNumericParser
5
+ class << self
6
+ # Parse numbers removing unneeded characters and replacing decimal separator
7
+ # through I18n. This will return a valid Ruby Numeric value (as String).
8
+ def parse(value)
9
+ if value.is_a?(String)
10
+ separator = I18n.t(:'number.format.separator')
11
+ value = value.gsub(/[^0-9\-#{separator}]/, '').gsub(separator, '.')
12
+ end
13
+ value
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,48 @@
1
+ # TODO: also override other methods like to_check_box_tag since they might contain numeric values?
2
+ # ActionView needs some patching too
3
+
4
+ ActionView::Helpers::InstanceTag.class_eval do
5
+ include ActionView::Helpers::NumberHelper
6
+
7
+ alias original_to_input_field_tag to_input_field_tag
8
+ def to_input_field_tag(field_type, options = {})
9
+ options.symbolize_keys!
10
+ # numbers and dates/times should be localized unless value is already defined
11
+ if object && options[:value].blank? && object.respond_to?(:column_for_attribute) && column = object.column_for_attribute(method_name)
12
+ # a little verbose
13
+ if column.number? || column.date? || column.time?
14
+ value = object.send(method_name)
15
+
16
+ if column.number? and field_type != 'hidden' and method_name != 'id'
17
+ number_options = I18n.t(:'number.format')
18
+ separator = options.delete(:separator) || number_options[:separator]
19
+ delimiter = options.delete(:delimiter) || number_options[:delimiter]
20
+ precision = options.delete(:precision) || number_options[:precision]
21
+ opts = { :separator => separator, :delimiter => delimiter, :precision => precision }
22
+ # integers don't need a precision
23
+ opts.merge!(:precision => 0) if column.type == :integer
24
+
25
+ options[:value] = number_with_precision(value, opts)
26
+ elsif column.date? || column.time?
27
+ options[:value] = value ? I18n.l(value, :format => options.delete(:format)) : nil
28
+ end
29
+ end
30
+ end
31
+
32
+ original_to_input_field_tag(field_type, options)
33
+ end
34
+ end
35
+
36
+ # TODO: does it make sense to also override FormTagHelper methods?
37
+ # ActionView::Helpers::FormTagHelper.class_eval do
38
+ # include ActionView::Helpers::NumberHelper
39
+ #
40
+ # alias original_text_field_tag text_field_tag
41
+ # def text_field_tag(name, value = nil, options = {})
42
+ # value = options.delete(:value) if options.key?(:value)
43
+ # if value.is_a?(Numeric)
44
+ # value = number_with_delimiter(value)
45
+ # end
46
+ # original_text_field_tag(name, value, options)
47
+ # end
48
+ # end
@@ -0,0 +1,47 @@
1
+ # let's hack into ActiveRecord a bit - everything at the lowest possible level, of course, so we minimalize side effects
2
+ ActiveRecord::ConnectionAdapters::Column.class_eval do
3
+ def date?
4
+ klass == Date
5
+ end
6
+
7
+ def time?
8
+ klass == Time
9
+ end
10
+ end
11
+
12
+ ActiveRecord::Base.class_eval do
13
+ def write_attribute_with_localization(attr_name, value)
14
+ if column = column_for_attribute(attr_name.to_s)
15
+ if column.date?
16
+ value = Date.parse_localized(value)
17
+ elsif column.time?
18
+ value = Time.parse_localized(value)
19
+ elsif column.number?
20
+ value = column.type_cast(convert_number_column_value_with_localization(value))
21
+ end
22
+ end
23
+ write_attribute_without_localization(attr_name, value)
24
+ end
25
+ alias_method_chain :write_attribute, :localization
26
+
27
+ # ugh
28
+ def self.define_write_method_for_time_zone_conversion(attr_name)
29
+ method_body = <<-EOV
30
+ def #{attr_name}=(time)
31
+ unless time.acts_like?(:time)
32
+ time = time.is_a?(String) ? (I18n.delocalization_enabled? ? Time.zone.parse_localized(time) : Time.zone.parse(time)) : time.to_time rescue time
33
+ end
34
+ time = time.in_time_zone rescue nil if time
35
+ write_attribute(:#{attr_name}, time)
36
+ end
37
+ EOV
38
+ evaluate_attribute_method attr_name, method_body, "#{attr_name}="
39
+ end
40
+
41
+ def convert_number_column_value_with_localization(value)
42
+ value = convert_number_column_value_without_localization(value)
43
+ value = Numeric.parse_localized(value) if I18n.delocalization_enabled?
44
+ value
45
+ end
46
+ alias_method_chain :convert_number_column_value, :localization
47
+ end
@@ -0,0 +1,7 @@
1
+ require 'delocalize/localized_date_time_parser'
2
+
3
+ ActiveSupport::TimeZone.class_eval do
4
+ def parse_localized(time_with_zone)
5
+ Delocalize::LocalizedDateTimeParser.parse(time_with_zone, self.class)
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ require 'delocalize/rails_ext/active_record'
2
+ require 'delocalize/rails_ext/action_view'
3
+ require 'delocalize/rails_ext/time_zone'
@@ -0,0 +1,9 @@
1
+ require 'delocalize/localized_date_time_parser'
2
+
3
+ Date.class_eval do
4
+ class << self
5
+ def parse_localized(date)
6
+ Delocalize::LocalizedDateTimeParser.parse(date, self)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ require 'delocalize/localized_date_time_parser'
2
+
3
+ DateTime.class_eval do
4
+ class << self
5
+ def parse_localized(datetime)
6
+ Delocalize::LocalizedDateTimeParser.parse(datetime, self)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ require 'delocalize/localized_numeric_parser'
2
+
3
+ Numeric.class_eval do
4
+ class << self
5
+ def parse_localized(value)
6
+ Delocalize::LocalizedNumericParser.parse(value)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ require 'delocalize/localized_date_time_parser'
2
+
3
+ Time.class_eval do
4
+ class << self
5
+ def parse_localized(time)
6
+ Delocalize::LocalizedDateTimeParser.parse(time, self)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,4 @@
1
+ require 'delocalize/ruby_ext/date'
2
+ require 'delocalize/ruby_ext/datetime'
3
+ require 'delocalize/ruby_ext/time'
4
+ require 'delocalize/ruby_ext/numeric'
data/lib/delocalize.rb ADDED
@@ -0,0 +1,4 @@
1
+ require 'delocalize/ruby_ext'
2
+ require 'delocalize/i18n_ext'
3
+ require 'delocalize/rails_ext'
4
+ require 'delocalize/localized_date_time_parser'
@@ -0,0 +1,21 @@
1
+ begin
2
+ require 'jeweler'
3
+ Jeweler::Tasks.new do |s|
4
+ s.name = "nested-delocalize"
5
+ s.summary = "Localized date/time and number parsing"
6
+ s.email = "formigarafa@gmail.com"
7
+ s.homepage = "http://github.com/formigarafa/delocalize"
8
+ s.description = "Delocalize is a tool for parsing localized dates/times and numbers. Fixed to working with nested models."
9
+ s.authors = ["Rafael Santos"]
10
+ s.files = FileList["init.rb",
11
+ "lib/**/*.rb",
12
+ "MIT-LICENSE",
13
+ "Rakefile",
14
+ "README",
15
+ "tasks/**/*.rb",
16
+ "VERSION"]
17
+ s.test_files = FileList["test/**/*.rb"]
18
+ end
19
+ rescue LoadError
20
+ puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
21
+ end
@@ -0,0 +1,8 @@
1
+ desc 'Generate documentation for the delocalize plugin.'
2
+ Rake::RDocTask.new(:rdoc) do |rdoc|
3
+ rdoc.rdoc_dir = 'rdoc'
4
+ rdoc.title = 'Delocalize'
5
+ rdoc.options << '--line-numbers' << '--inline-source'
6
+ rdoc.rdoc_files.include('README')
7
+ rdoc.rdoc_files.include('lib/**/*.rb')
8
+ end
data/tasks/testing.rb ADDED
@@ -0,0 +1,7 @@
1
+ desc 'Test the delocalize plugin.'
2
+ Rake::TestTask.new(:test) do |t|
3
+ t.libs << 'lib'
4
+ t.libs << 'test'
5
+ t.pattern = 'test/**/*_test.rb'
6
+ t.verbose = true
7
+ end
@@ -0,0 +1,230 @@
1
+ require File.dirname(__FILE__) + '/test_helper'
2
+
3
+ class DelocalizeActiveRecordTest < ActiveRecord::TestCase
4
+ def setup
5
+ Time.zone = 'Berlin' # make sure everything works as expected with TimeWithZone
6
+ @product = Product.new
7
+ end
8
+
9
+ test "delocalizes localized number" do
10
+ @product.price = '1.299,99'
11
+ assert_equal 1299.99, @product.price
12
+
13
+ @product.price = '-1.299,99'
14
+ assert_equal -1299.99, @product.price
15
+ end
16
+
17
+ test "delocalizes localized date with year" do
18
+ date = Date.civil(2009, 10, 19)
19
+
20
+ @product.released_on = '19. Oktober 2009'
21
+ assert_equal date, @product.released_on
22
+
23
+ @product.released_on = '19.10.2009'
24
+ assert_equal date, @product.released_on
25
+ end
26
+
27
+ test "delocalizes localized date without year" do
28
+ date = Date.civil(Date.today.year, 10, 19)
29
+
30
+ @product.released_on = '19. Okt'
31
+ assert_equal date, @product.released_on
32
+ end
33
+
34
+ test "delocalizes localized datetime with year" do
35
+ time = Time.local(2009, 3, 1, 12, 0, 0)
36
+
37
+ @product.published_at = 'Sonntag, 1. März 2009, 12:00 Uhr'
38
+ assert_equal time, @product.published_at
39
+
40
+ @product.published_at = '1. März 2009, 12:00 Uhr'
41
+ assert_equal time, @product.published_at
42
+ end
43
+
44
+ test "delocalizes localized datetime without year" do
45
+ time = Time.local(Date.today.year, 3, 1, 12, 0, 0)
46
+
47
+ @product.published_at = '1. März, 12:00 Uhr'
48
+ assert_equal time, @product.published_at
49
+ end
50
+
51
+ test "delocalizes localized time" do
52
+ now = Time.current
53
+ time = Time.local(now.year, now.month, now.day, 9, 0, 0)
54
+ @product.cant_think_of_a_sensible_time_field = '09:00 Uhr'
55
+ assert_equal time, @product.cant_think_of_a_sensible_time_field
56
+ end
57
+
58
+ test "uses default parse if format isn't found" do
59
+ date = Date.civil(2009, 10, 19)
60
+
61
+ @product.released_on = '2009/10/19'
62
+ assert_equal date, @product.released_on
63
+
64
+ time = Time.local(2009, 3, 1, 12, 0, 0)
65
+ @product.published_at = '2009/03/01 12:00'
66
+ assert_equal time, @product.published_at
67
+
68
+ now = Time.current
69
+ time = Time.local(now.year, now.month, now.day, 9, 0, 0)
70
+ @product.cant_think_of_a_sensible_time_field = '09:00'
71
+ assert_equal time, @product.cant_think_of_a_sensible_time_field
72
+ end
73
+
74
+ test "should return nil if the input is empty or invalid" do
75
+ @product.released_on = ""
76
+ assert_nil @product.released_on
77
+
78
+ @product.released_on = "aa"
79
+ assert_nil @product.released_on
80
+ end
81
+
82
+ test "doesn't raise when attribute is nil" do
83
+ assert_nothing_raised {
84
+ @product.price = nil
85
+ @product.released_on = nil
86
+ @product.published_at = nil
87
+ @product.cant_think_of_a_sensible_time_field = nil
88
+ }
89
+ end
90
+
91
+ test "uses default formats if enable_delocalization is false" do
92
+ I18n.enable_delocalization = false
93
+
94
+ @product.price = '1299.99'
95
+ assert_equal 1299.99, @product.price
96
+
97
+ @product.price = '-1299.99'
98
+ assert_equal -1299.99, @product.price
99
+ end
100
+
101
+ test "uses default formats if called with with_delocalization_disabled" do
102
+ I18n.with_delocalization_disabled do
103
+ @product.price = '1299.99'
104
+ assert_equal 1299.99, @product.price
105
+
106
+ @product.price = '-1299.99'
107
+ assert_equal -1299.99, @product.price
108
+ end
109
+ end
110
+
111
+ test "uses localized parsing if called with with_delocalization_enabled" do
112
+ I18n.with_delocalization_enabled do
113
+ @product.price = '1.299,99'
114
+ assert_equal 1299.99, @product.price
115
+
116
+ @product.price = '-1.299,99'
117
+ assert_equal -1299.99, @product.price
118
+ end
119
+ end
120
+
121
+ test "dirty attributes must detect changes in decimal columns" do
122
+ @product.price = 10
123
+ @product.save
124
+ @product.price = "10,34"
125
+ assert @product.price_changed?
126
+ end
127
+
128
+ test "dirty attributes must detect changes in float columns" do
129
+ @product.weight = 10
130
+ @product.save
131
+ @product.weight = "10,34"
132
+ assert @product.weight_changed?
133
+ end
134
+ end
135
+
136
+ class DelocalizeActionViewTest < ActionView::TestCase
137
+ include ActionView::Helpers::FormHelper
138
+
139
+ def setup
140
+ Time.zone = 'Berlin' # make sure everything works as expected with TimeWithZone
141
+ @product = Product.new
142
+ end
143
+
144
+ test "shows text field using formatted number" do
145
+ @product.price = 1299.9
146
+ assert_dom_equal '<input id="product_price" name="product[price]" size="30" type="text" value="1.299,90" />',
147
+ text_field(:product, :price)
148
+ end
149
+
150
+ test "shows text field using formatted number with options" do
151
+ @product.price = 1299.995
152
+ assert_dom_equal '<input id="product_price" name="product[price]" size="30" type="text" value="1,299.995" />',
153
+ text_field(:product, :price, :precision => 3, :delimiter => ',', :separator => '.')
154
+ end
155
+
156
+ test "shows text field using formatted number without precision if column is an integer" do
157
+ @product.times_sold = 20
158
+ assert_dom_equal '<input id="product_times_sold" name="product[times_sold]" size="30" type="text" value="20" />',
159
+ text_field(:product, :times_sold)
160
+
161
+ @product.times_sold = 2000
162
+ assert_dom_equal '<input id="product_times_sold" name="product[times_sold]" size="30" type="text" value="2.000" />',
163
+ text_field(:product, :times_sold)
164
+ end
165
+
166
+ test "shows text field using formatted date" do
167
+ @product.released_on = Date.civil(2009, 10, 19)
168
+ assert_dom_equal '<input id="product_released_on" name="product[released_on]" size="30" type="text" value="19.10.2009" />',
169
+ text_field(:product, :released_on)
170
+ end
171
+
172
+ test "shows text field using formatted date and time" do
173
+ @product.published_at = Time.local(2009, 3, 1, 12, 0, 0)
174
+ # careful - leading whitespace with %e
175
+ assert_dom_equal '<input id="product_published_at" name="product[published_at]" size="30" type="text" value="Sonntag, 1. März 2009, 12:00 Uhr" />',
176
+ text_field(:product, :published_at)
177
+ end
178
+
179
+ test "shows text field using formatted date with format" do
180
+ @product.released_on = Date.civil(2009, 10, 19)
181
+ assert_dom_equal '<input id="product_released_on" name="product[released_on]" size="30" type="text" value="19. Oktober 2009" />',
182
+ text_field(:product, :released_on, :format => :long)
183
+ end
184
+
185
+ test "shows text field using formatted date and time with format" do
186
+ @product.published_at = Time.local(2009, 3, 1, 12, 0, 0)
187
+ # careful - leading whitespace with %e
188
+ assert_dom_equal '<input id="product_published_at" name="product[published_at]" size="30" type="text" value=" 1. März, 12:00 Uhr" />',
189
+ text_field(:product, :published_at, :format => :short)
190
+ end
191
+
192
+ test "shows text field using formatted time with format" do
193
+ @product.cant_think_of_a_sensible_time_field = Time.local(2009, 3, 1, 9, 0, 0)
194
+ assert_dom_equal '<input id="product_cant_think_of_a_sensible_time_field" name="product[cant_think_of_a_sensible_time_field]" size="30" type="text" value="09:00 Uhr" />',
195
+ text_field(:product, :cant_think_of_a_sensible_time_field, :format => :time)
196
+ end
197
+
198
+ test "doesn't raise an exception when object is nil" do
199
+ assert_nothing_raised {
200
+ text_field(:not_here, :a_text_field)
201
+ }
202
+ end
203
+
204
+ test "doesn't raise for nil Date/Time" do
205
+ @product.published_at, @product.released_on, @product.cant_think_of_a_sensible_time_field = nil
206
+ assert_nothing_raised {
207
+ text_field(:product, :published_at)
208
+ text_field(:product, :released_on)
209
+ text_field(:product, :cant_think_of_a_sensible_time_field)
210
+ }
211
+ end
212
+
213
+ test "doesn't override given :value" do
214
+ @product.price = 1299.9
215
+ assert_dom_equal '<input id="product_price" name="product[price]" size="30" type="text" value="1.499,90" />',
216
+ text_field(:product, :price, :value => "1.499,90")
217
+ end
218
+
219
+ test "doesn't raise an exception when object isn't an ActiveReccord" do
220
+ @product = NonArProduct.new
221
+ assert_nothing_raised {
222
+ text_field(:product, :name)
223
+ text_field(:product, :times_sold)
224
+ text_field(:product, :published_at)
225
+ text_field(:product, :released_on)
226
+ text_field(:product, :cant_think_of_a_sensible_time_field)
227
+ text_field(:product, :price, :value => "1.499,90")
228
+ }
229
+ end
230
+ end
@@ -0,0 +1,10 @@
1
+ # Filters added to this controller apply to all controllers in the application.
2
+ # Likewise, all the methods added will be available for all controllers.
3
+
4
+ class ApplicationController < ActionController::Base
5
+ helper :all # include all helpers, all the time
6
+ protect_from_forgery # See ActionController::RequestForgeryProtection for details
7
+
8
+ # Scrub sensitive parameters from your log
9
+ filter_parameter_logging :password
10
+ end
@@ -0,0 +1,110 @@
1
+ # Don't change this file!
2
+ # Configure your app in config/environment.rb and config/environments/*.rb
3
+
4
+ RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
5
+
6
+ module Rails
7
+ class << self
8
+ def boot!
9
+ unless booted?
10
+ preinitialize
11
+ pick_boot.run
12
+ end
13
+ end
14
+
15
+ def booted?
16
+ defined? Rails::Initializer
17
+ end
18
+
19
+ def pick_boot
20
+ (vendor_rails? ? VendorBoot : GemBoot).new
21
+ end
22
+
23
+ def vendor_rails?
24
+ File.exist?("#{RAILS_ROOT}/vendor/rails")
25
+ end
26
+
27
+ def preinitialize
28
+ load(preinitializer_path) if File.exist?(preinitializer_path)
29
+ end
30
+
31
+ def preinitializer_path
32
+ "#{RAILS_ROOT}/config/preinitializer.rb"
33
+ end
34
+ end
35
+
36
+ class Boot
37
+ def run
38
+ load_initializer
39
+ Rails::Initializer.run(:set_load_path)
40
+ end
41
+ end
42
+
43
+ class VendorBoot < Boot
44
+ def load_initializer
45
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
46
+ Rails::Initializer.run(:install_gem_spec_stubs)
47
+ Rails::GemDependency.add_frozen_gem_path
48
+ end
49
+ end
50
+
51
+ class GemBoot < Boot
52
+ def load_initializer
53
+ self.class.load_rubygems
54
+ load_rails_gem
55
+ require 'initializer'
56
+ end
57
+
58
+ def load_rails_gem
59
+ if version = self.class.gem_version
60
+ gem 'rails', version
61
+ else
62
+ gem 'rails'
63
+ end
64
+ rescue Gem::LoadError => load_error
65
+ $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
66
+ exit 1
67
+ end
68
+
69
+ class << self
70
+ def rubygems_version
71
+ Gem::RubyGemsVersion rescue nil
72
+ end
73
+
74
+ def gem_version
75
+ if defined? RAILS_GEM_VERSION
76
+ RAILS_GEM_VERSION
77
+ elsif ENV.include?('RAILS_GEM_VERSION')
78
+ ENV['RAILS_GEM_VERSION']
79
+ else
80
+ parse_gem_version(read_environment_rb)
81
+ end
82
+ end
83
+
84
+ def load_rubygems
85
+ min_version = '1.3.2'
86
+ require 'rubygems'
87
+ unless rubygems_version >= min_version
88
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
89
+ exit 1
90
+ end
91
+
92
+ rescue LoadError
93
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
94
+ exit 1
95
+ end
96
+
97
+ def parse_gem_version(text)
98
+ $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
99
+ end
100
+
101
+ private
102
+ def read_environment_rb
103
+ File.read("#{RAILS_ROOT}/config/environment.rb")
104
+ end
105
+ end
106
+ end
107
+ end
108
+
109
+ # All that for this:
110
+ Rails.boot!
@@ -0,0 +1,17 @@
1
+ # Be sure to restart your server when you modify this file
2
+
3
+ # Specifies gem version of Rails to use when vendor/rails is not present
4
+ RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
5
+
6
+ # Bootstrap the Rails environment, frameworks, and default configuration
7
+ require File.join(File.dirname(__FILE__), 'boot')
8
+
9
+ Rails::Initializer.run do |config|
10
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
11
+ # Run "rake -D time" for a list of tasks for finding time zone names.
12
+ # config.time_zone = 'UTC'
13
+
14
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
15
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
16
+ # config.i18n.default_locale = :en
17
+ end
@@ -0,0 +1,28 @@
1
+ # Settings specified here will take precedence over those in config/environment.rb
2
+
3
+ # The test environment is used exclusively to run your application's
4
+ # test suite. You never need to work with it otherwise. Remember that
5
+ # your test database is "scratch space" for the test suite and is wiped
6
+ # and recreated between test runs. Don't rely on the data there!
7
+ config.cache_classes = true
8
+
9
+ # Log error messages when you accidentally call methods on nil.
10
+ config.whiny_nils = true
11
+
12
+ # Show full error reports and disable caching
13
+ config.action_controller.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+ config.action_view.cache_template_loading = true
16
+
17
+ # Disable request forgery protection in test environment
18
+ config.action_controller.allow_forgery_protection = false
19
+
20
+ # Tell Action Mailer not to deliver emails to the real world.
21
+ # The :test delivery method accumulates sent emails in the
22
+ # ActionMailer::Base.deliveries array.
23
+ config.action_mailer.delivery_method = :test
24
+
25
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
26
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
27
+ # like if you have constraints or database-specific column types
28
+ # config.active_record.schema_format = :sql
@@ -0,0 +1,21 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # These settings change the behavior of Rails 2 apps and will be defaults
4
+ # for Rails 3. You can remove this initializer when Rails 3 is released.
5
+
6
+ if defined?(ActiveRecord)
7
+ # Include Active Record class name as root for JSON serialized output.
8
+ ActiveRecord::Base.include_root_in_json = true
9
+
10
+ # Store the full class name (including module namespace) in STI type column.
11
+ ActiveRecord::Base.store_full_sti_class = true
12
+ end
13
+
14
+ ActionController::Routing.generate_best_match = false
15
+
16
+ # Use ISO 8601 format for JSON serialized times and dates.
17
+ ActiveSupport.use_standard_json_time_format = true
18
+
19
+ # Don't escape HTML entities in JSON, leave that for the #json_escape helper.
20
+ # if you're including raw json in an HTML page.
21
+ ActiveSupport.escape_html_entities_in_json = false
@@ -0,0 +1,15 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Your secret key for verifying cookie session data integrity.
4
+ # If you change this key, all old sessions will become invalid!
5
+ # Make sure the secret is at least 30 characters and all random,
6
+ # no regular words or you'll be exposed to dictionary attacks.
7
+ ActionController::Base.session = {
8
+ :key => '_rails_app_session',
9
+ :secret => '89e8147901a0d7c221ac130e0ded3eeab6dab4a97127255909f08fedaae371918b41dec9d4d75c5b27a55c3772d43c2b6a3cbac232c5cc2ce4b8ec22242f5e60'
10
+ }
11
+
12
+ # Use the database for sessions instead of the cookie-based default,
13
+ # which shouldn't be used to store highly confidential information
14
+ # (create the session table with "rake db:sessions:create")
15
+ # ActionController::Base.session_store = :active_record_store
@@ -0,0 +1,4 @@
1
+ ActionController::Routing::Routes.draw do |map|
2
+ map.connect ':controller/:action/:id'
3
+ map.connect ':controller/:action/:id.:format'
4
+ end
@@ -0,0 +1,73 @@
1
+ ENV["RAILS_ENV"] = "test"
2
+ #require File.expand_path(File.dirname(__FILE__) + "/../../../../config/environment")
3
+ require File.expand_path(File.dirname(__FILE__) + "/rails_app/config/environment")
4
+ require 'test_help'
5
+
6
+ require 'rubygems'
7
+ require 'active_record'
8
+ require 'active_record/test_case'
9
+ require 'action_view'
10
+ require 'action_view/test_case'
11
+
12
+ I18n.backend.store_translations :de, {
13
+ :date => {
14
+ :input => {
15
+ :formats => [:long, :short, :default]
16
+ },
17
+ :formats => {
18
+ :default => "%d.%m.%Y",
19
+ :short => "%e. %b",
20
+ :long => "%e. %B %Y",
21
+ :only_day => "%e"
22
+ },
23
+ :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag),
24
+ :abbr_day_names => %w(So Mo Di Mi Do Fr Sa),
25
+ :month_names => [nil] + %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember),
26
+ :abbr_month_names => [nil] + %w(Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez)
27
+ },
28
+ :time => {
29
+ :input => {
30
+ :formats => [:long, :medium, :short, :default, :time]
31
+ },
32
+ :formats => {
33
+ :default => "%A, %e. %B %Y, %H:%M Uhr",
34
+ :short => "%e. %B, %H:%M Uhr",
35
+ :medium => "%e. %B %Y, %H:%M Uhr",
36
+ :long => "%A, %e. %B %Y, %H:%M Uhr",
37
+ :time => "%H:%M Uhr"
38
+ },
39
+ :am => 'vormittags',
40
+ :pm => 'nachmittags'
41
+ },
42
+ :number => {
43
+ :format => {
44
+ :precision => 2,
45
+ :separator => ',',
46
+ :delimiter => '.'
47
+ }
48
+ }
49
+ }
50
+
51
+ I18n.locale = :de
52
+
53
+ class NonArProduct
54
+ attr_accessor :name, :price, :times_sold,
55
+ :cant_think_of_a_sensible_time_field,
56
+ :released_on, :published_at
57
+ end
58
+
59
+ class Product < ActiveRecord::Base
60
+ end
61
+
62
+ config = YAML.load_file(File.dirname(__FILE__) + '/database.yml')
63
+ ActiveRecord::Base.establish_connection(config['test'])
64
+
65
+ ActiveRecord::Base.connection.create_table :products do |t|
66
+ t.string :name
67
+ t.date :released_on
68
+ t.datetime :published_at
69
+ t.time :cant_think_of_a_sensible_time_field
70
+ t.decimal :price
71
+ t.float :weight
72
+ t.integer :times_sold
73
+ end
metadata ADDED
@@ -0,0 +1,90 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nested-delocalize
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 0
7
+ - 1
8
+ - 8
9
+ version: 0.1.8
10
+ platform: ruby
11
+ authors:
12
+ - Rafael Santos
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-03-08 00:00:00 -03:00
18
+ default_executable:
19
+ dependencies: []
20
+
21
+ description: Delocalize is a tool for parsing localized dates/times and numbers. Fixed to working with nested models.
22
+ email: formigarafa@gmail.com
23
+ executables: []
24
+
25
+ extensions: []
26
+
27
+ extra_rdoc_files:
28
+ - README
29
+ files:
30
+ - MIT-LICENSE
31
+ - README
32
+ - Rakefile
33
+ - VERSION
34
+ - init.rb
35
+ - lib/delocalize.rb
36
+ - lib/delocalize/i18n_ext.rb
37
+ - lib/delocalize/localized_date_time_parser.rb
38
+ - lib/delocalize/localized_numeric_parser.rb
39
+ - lib/delocalize/rails_ext.rb
40
+ - lib/delocalize/rails_ext/action_view.rb
41
+ - lib/delocalize/rails_ext/active_record.rb
42
+ - lib/delocalize/rails_ext/time_zone.rb
43
+ - lib/delocalize/ruby_ext.rb
44
+ - lib/delocalize/ruby_ext/date.rb
45
+ - lib/delocalize/ruby_ext/datetime.rb
46
+ - lib/delocalize/ruby_ext/numeric.rb
47
+ - lib/delocalize/ruby_ext/time.rb
48
+ - tasks/distribution.rb
49
+ - tasks/documentation.rb
50
+ - tasks/testing.rb
51
+ has_rdoc: true
52
+ homepage: http://github.com/formigarafa/delocalize
53
+ licenses: []
54
+
55
+ post_install_message:
56
+ rdoc_options:
57
+ - --charset=UTF-8
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ segments:
65
+ - 0
66
+ version: "0"
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ segments:
72
+ - 0
73
+ version: "0"
74
+ requirements: []
75
+
76
+ rubyforge_project:
77
+ rubygems_version: 1.3.6
78
+ signing_key:
79
+ specification_version: 3
80
+ summary: Localized date/time and number parsing
81
+ test_files:
82
+ - test/delocalize_test.rb
83
+ - test/rails_app/app/controllers/application_controller.rb
84
+ - test/rails_app/config/boot.rb
85
+ - test/rails_app/config/environment.rb
86
+ - test/rails_app/config/environments/test.rb
87
+ - test/rails_app/config/initializers/new_rails_defaults.rb
88
+ - test/rails_app/config/initializers/session_store.rb
89
+ - test/rails_app/config/routes.rb
90
+ - test/test_helper.rb