Code Monkey home page Code Monkey logo

delocalize's Introduction

delocalize

Build Status

delocalize provides localized date/time and number parsing functionality for Rails.

Compatibility

This gem requires the following versions:

  • Ruby >= 2.1.10 (Ruby >= 1.9.2 should work but isn't officially supported)
  • Rails >= 4.2 (earlier versions including probably even Rails 1 should work but aren't officially supported)

Check the Travis configuration in order to see which configurations we are testing.

Installation

You can use delocalize as a gem. Using delocalize as a Rails plugin has been discontinued and is no supported. If you want/need to use delocalize as a plugin (I really don't see a reason why you'd want to), consider using the 0-2-stable branch.

Rails 3 and above

To use delocalize, put the following gem requirement in your Gemfile:

gem "delocalize"

Rails 2

Note: Official support for Rails 2 has been discontinued. However, due to the way this gem has been rewritten for its 1.0.0 release, it should work with Rails 2 just fine. If you run into any problems, consider filing an issue.

To use delocalize, put the following gem requirement in your environment.rb:

config.gem "delocalize", :source => 'http://gemcutter.org'

In Rails 2.3, alternatively, you can use it with Bundler. See http://gembundler.com/rails23.html for instructions.

What does it do? And how do I use it?

Delocalize, just as the name suggest, does pretty much the opposite of localize.

In the grey past, if you want your users to be able to input localized data, such as dates and numbers, you had to manually override attribute accessors:

def price=(price)
  write_attribute(:price, price.gsub(',', '.'))
end

You also had to take care of proper formatting in forms on the frontend so people would see localized values in their forms.

Delocalize does most of this under the covers. All you need is a simple setup in your controllers and your regular translation data (as YAML or Ruby file) where you need Rails' standard translations.

Controller setup

The approach used in delocalize is based on Rails' own strong_parameters. In fact, if you are on Rails 3 with the strong_parameters gem installed or Rails 4 (which includes it by default), delocalize is mixed straight into the provided ActionController::Parameters class. Otherwise it uses its own similar class (Delocalize::Parameters).

You can then use delocalize as you would use strong_parameters:

class ProductsController < ApplicationController
  def create
    Product.create(product_params)
  end

private

  def product_params
    delocalize_config = { :released_on => :date, :available_until => :time, :price => :number }
    # with strong_parameters
    params.require(:product).permit(*delocalize_config.keys).delocalize(delocalize_config)
    # without strong_parameters
    params.delocalize(:product => delocalize_config)[:product]
    # or
    params[:product].delocalize(delocalize_config)
  end

end

If you want to delocalize only certain parameters, configure those parameters and leave the others out – they will be kept as they are.

Views

Delocalize doesn't automatically localize your data again (yet). There are various reasons for that but the main reasons are:

  • It's hard to do this properly with some amount of flexibility for you as the user of the gem without crazy hacks of Rails internals (a problem that delocalize previously suffered from).
  • Personally I feel that presentation logic (including forms) should be split out into separate objects (presenters, decorators, form objects and the like).

I might change my mind but as it stands but for the time being the gist is: Wherever you want to see localized values, you have to localize them yourself.

Examples:

text_field :product, :released_on, :value => product.released_on ? l(product.released_on) : nil
text_field_tag 'product[price]', number_with_precision(product.price, :precision => 2)

You can of course use something like the Draper gem or the great Reform gem to wrap your actual object and override the relevant accessors.

Check out how this can be done in the demo app.

There's also a wiki page on how to write a custom input for SimpleForm.

Locale setup

In addition to your controller setup, you also need to configure your locale file(s). If you intend to use delocalize, you probably have a working locale file anyways. In this case, you only need to add two extra keys: date.input.formats and time.input.formats.

Assuming you want to use all of delocalize's parsers (date, time, number), the required keys are:

  • number.format.delimiter
  • number.format.separator
  • date.input.formats
  • time.input.formats
  • date.formats.SOME_FORMAT for all formats specified in date.input.formats
  • time.formats.SOME_FORMAT for all formats specified in time.input.formats
de:
  number:
    format:
      separator: ','
      delimiter: '.'
  date:
    input:
      formats: [:default, :long, :short] # <- this and ...

    formats:
      default: "%d.%m.%Y"
      short: "%e. %b"
      long: "%e. %B %Y"
      only_day: "%e"

    day_names: [Sonntag, Montag, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag]
    abbr_day_names: [So, Mo, Di, Mi, Do, Fr, Sa]
    month_names: [~, Januar, Februar, März, April, Mai, Juni, Juli, August, September, Oktober, November, Dezember]
    abbr_month_names: [~, Jan, Feb, Mär, Apr, Mai, Jun, Jul, Aug, Sep, Okt, Nov, Dez]
    order: [ :day, :month, :year ]

  time:
    input:
      formats: [:long, :medium, :short, :default, :time] # <- ... this are the only non-standard keys
    formats:
      default: "%A, %e. %B %Y, %H:%M Uhr"
      short: "%e. %B, %H:%M Uhr"
      long: "%A, %e. %B %Y, %H:%M Uhr"
      time: "%H:%M"

    am: "vormittags"
    pm: "nachmittags"

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.

Be careful with formats containing only numbers: It's very hard to produce reliable matches if you provide multiple strictly numeric formats!

Contributors and Copyright

Here is a list of all people who ever contributed to delocalize.

Copyright (c) 2009-2017 Clemens Kofler [email protected] http://www.railway.at/ Released under the MIT license

delocalize's People

Contributors

bforma avatar carlosantoniodasilva avatar daniel-rikowski avatar defv avatar dexterthedragon avatar fabiomr avatar flameeyes avatar fmluizao avatar jackiig avatar jan-at-ctt avatar parndt avatar ralph avatar rspace avatar saten avatar stepahn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

delocalize's Issues

Does not recognize date with single digits

I have defined a date format as:

  • default: "%d/%m/%Y"

But when a user submits a date with a single digit day and month (Example: "1/3/2011"), it doesn't detect the format and so it falls back to the american format of "%m/%d/%Y"

Which would mean that the date is parsed as 3rd January 2001, instead of the correct 1st March 2011

Issues with validates_numericallity and rails 3

To reproduce, include a validation like this:

validates_numericality_of :prazo, :only_integer => true, :allow_nil => false, :message => "it's not a valid integer"

it will validate even if value is passed as a float.

not working in rails/ruby 2

i got the following error when start the rails server in local
"/home/san/.rvm/gems/ruby-2.0.0-p247@r4/gems/activesupport-4.0.0/lib/active_support/core_ext/module/aliasing.rb:32:in alias_method': undefined methodconvert_number_column_value' for class `ActiveRecord::Base' (NameError)
"
my Gemfile:
gem "delocalize",:git => "git://github.com/clemens/delocalize.git",:branch => '0-2-stable'

Error delocalizing params with nested attributes

I get an undefined method 'stringify_keys' for nil:NilClass error when posting a model update that includes nested attributes for a child model.

The workaround was to add child_attributes: {} in the meantime to proceed, as below. Not sure what the issue is and unfortunately don't have the time to look further.

params.permit( 
        parent: [
           :name,
           :cash,
           :child_attributes => [:name]
        ]).delocalize({ 
          parent: { 
            cash: :number, 
            child_attributes: {}
          }
        })

Setting an invalid value in a time field while doing update_attributes! sets the value to nil

I noticed that setting an invalid time value causes the value to get saved as nil without any validations failing. For an instance,

some_model_intance.update_attributes!(a_datetime_field: "blah")

succeeds with the a_datetime_field value being set to nil.

This is happening due to the way Time.zone.parse_localized(time) is handling parsing of invalid strings in the setter in active_record_rails3.rb and active_record_rails4.rb.

In this situation, shouldn't the expected behaviour be to fail and preserve the old value?

Error when providing default values as Time

I'am filing default values into datetime database object on creation time, when new record is created.

@doc.time_created = Time.now.localtime # same with Time.now

But in the input field I get values which are in UTC time. For example I live in Ljubljana/Slovenia which is UTC+2h and current time is 9:50.

Time.now.localtime => 2012-08-13 09:50:06 +0200

value in input field is 13.08.2012 07:50. Which is wrong.

My current workaround is
@doc.time_created = Time.now.strftime('%d.%m.%Y %H:%M')

which looks silly to me ;-( Or am I doing something wrong.

by
TheR

P.S.
time:
formats:
default: ! '%d.%m.%Y %H:%M'
long: ! '%d. %B, %Y %H:%M'
short: ! '%d. %b %H:%M'

French Date issue. Probably Regexp fail?

Hey Guys.
I have a trouble with parsing :fr date "Févr. 12, 2015" to :en format.

Few examples from my console below:

$: date
=> "Févr. 12, 2015"
$: Delocalize::LocalizedDateTimeParser.parse(date, Date)
=> Sun, 05 Apr 2015
$: I18n.l(DateTime.parse('Feb 12 2015'))
=> "12 février 2015 00h 00min 00s"
$: I18n.l(DateTime.parse('Feb 12 2015'), format: '%b %d, %Y')
=> "Févr. 12, 2015"
$: date =  I18n.l(DateTime.parse('Mar 12 2015'), format: '%b %d, %Y')
=> "Mars 12, 2015"
$: Delocalize::LocalizedDateTimeParser.parse(date, Date)
=> Sun, 05 Apr 2015

So, as you can see, something strange happens with my code :(.

actually, i've implemented quickfix at my project to push it live, but i want to get more clear explanation - where i'm wrong?

here is my quickfix::
lib/extensions/localized_date_time_parser.rb

class << Delocalize::LocalizedDateTimeParser

  private
  def translate_month_and_day_names(datetime)

    translated = [:month_names, :abbr_month_names, :day_names, :abbr_day_names].map do |key|
      I18n.t(key, :scope => :date)
    end.flatten.compact

    original = (Date::MONTHNAMES + Date::ABBR_MONTHNAMES + Date::DAYNAMES + Date::ABBR_DAYNAMES).compact
    #translated.each_with_index { |name, i| datetime.gsub!(/\b#{name}\b/, original[i]) }
    translated.each_with_index { |name, i| datetime.gsub!(/\b#{name}/, original[i]) }
  end

end

Demo application not available

There are some links* in the documentation pointing to https://github.com/clemens/delocalize_demo, which should be a demo application but is currently not available. Could this demo application be resurrected?

* I found two: "Find a demo application here." at the start of the README.markdown and "Check out how this can be done in the demo app." under "Views" in the same file.

is localized_date_time_parser.rb thread safe?

Hi,

From localized_date_time_parser.rb - line 64:

(@input_formats ||= {})[type] ||= I18n.t(:"#{type}.formats").slice(*I18n.t(:"#{type}.input.formats")).values

Is the use of a class variable (@input_formats) thread safe in Rails?

We've been using the plugin version of delocalize and when we released the app to production (Apache with Phusion Passenger) targeting a diverse user base (multiple cultures / locales) we immediately started getting reports dates being rejected.

If the user's locale used mm/dd/yyyy then occasionally 12/01/2011 (Dec 12 2011) was rejected. Same for dd/mm/yyyy - 01/12/2011 (Dec 01 2011 in UK).

I think the issue is Phusion Passenger "reuses" threads so the class variable @input_formats is sometimes already set from the last user thus treating a US user like a UK user.

After debugging we modified localized_date_time_parser to simply return the formats each time:

I18n.t(:"#{type}.formats", :locale => Thread.current[:current_locale]).slice(*I18n.t(:"#{type}.input.formats", :locale => Thread.current[:current_locale])).values

The Thread.current[:current_locale] is set in our application_controller for each request. This stopped the issue.

I'm not a Rails / Phusion Passenger threading expert so thought I'd pass along in case there's an issue in the gem / plugin or I'm going about things the wrong way.

Thanks for the great software and hope this helps.

Shawn

Parsing a localized date

I've installed delocalize and rails-i18n to provide datetime locales, I'm trying to parse this italian date:

Sabato 19 Ottobre 2013 20:30

which is basically

Saturday 19th October 2013 20:30

however DateTIme.parse returns 19 Oct 2014 (it parses just the day number). I18n.locale is :it, is there something else I have to config to parse the italian date?

Delocalize::LocalizedDateTimeParser#default_parse accepts invalid dates

I had a very ugly bug that in my tests my application suddenly started to accept invalid leap-year dates when installing delocalize. I went to delocalize, checked it code, run it's test, added a test: It never accepted invalid dates. But when run from my application (script/console), it suddenly started to parse invalid dates like "29. Februar 2009" which became "1. März 2009" in my tested models.

I tracked this down to be a nasty bug in your tests: Your tests pretend that every user has the [:date,:input,:formats] array set - I didn't. This makes my application (but not your tests) fallback to the "default_parse" method which - due to its implementation using Time.zone.local to convert dates - makes 2009/2/29 a valid date by transforming it to 2010/3/1. :-(

I'm preparing a test in my delocalize fork for you to work with on a fix.

New controller-side paradigm not working for me

We've been using the delocalize gem since Rails 3.1. I just upgraded to Rails 4.2 and delocalize 0.4.0 was broke so I decided to go ahead and upgrade to the latest branch. I noticed, and I read your dissertation on why you undid delocalize's "magic". I'm not sure that moving from convention to configuration is the way to go, but in this case, this is causing me some serious problems. I have one use case where we have an incredibly complex parameters hash coming through, with nested attributes within nested attributes, and with 0.4.0, this was "magically" handled. All dates entered magically delocalized because they came right from the view that way. Now I have to explicitly configure them, which is difficult with this nested parameters hash, but my bigger problem is we very often add additional fields to this hash, and the programmers responsible never had to worry about "oh, the field I am adding is a date, better add it to the delocalize config hash".

Anyway, thought I'd just mention that sometimes that "magic" solves problems elegantly for us. That magic is why Ruby is better than Java.

It should not raise NoMethodError when helper object is nil

I did not investigate this, but it seems that the desirable behavior should be to just ignore conversion when the object in helper is nil (like in Rails). For example:

text_field :person, :name

If person is nil, it throws an exception in the following line:
[...]/rails_ext/action_view.rb:10:in `to_input_field_tag'. It should not to do so.

Fix in regexp

Hi!

I thinkg the substitution for '%e' format should be: "([\w\s]?\d{1,2})" instead only "(\w?\d{1,2})")"

date = Date.civil(2010, 9, 8)
date.strftime("%e/%m/%Y") => " 8/09/2010"

Rails 3 does not have define_write_method_for_time_zone_conversion anymore

rails_ext/active_record.rb overwrites ActiveRecord::Base.define_write_method_for_time_zone_conversion to handle time zone. Unfortunately, define_write_method_for_time_zone_conversion method does not exist in Rails 3 anymore (3.0.1). One symptom of this is the fact that assigning string '12/31/2010' to a datetime field when locale is set to :en and the following configuration in config/locales/en.yml sets the field to null:

en:
time:
input:
formats: [:default, :long, :short]

formats:
  default: "%m/%d/%Y %H:%M"
  ....

No delocalize code is run in the above scenario, until is too late: write_attribute_with_localization(attr_name, nil). Probably, the method that has to be overwritten in Rails 3 is define_method_attribute= from ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods

Rails 4.2 compatibility

Once again the new Rails version is incompatible with delocalize, because the internal API regarding type casts of attributes has changed. (for the better imho)

I've spend some time on this and created a monkey patch which makes the current 0.4 release work with Rails 4.2. https://gist.github.com/daniel-rikowski/fd09dc2cc82ce28e7986

I'm not sure if this works 100%, but at least all my tests are green.

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Regular expression for date time format does not escape regexp sensitive characters

The method apply regex at https://github.com/clemens/delocalize/blob/master/lib/delocalize/parsers/date_time.rb#L84 does not escape regex sensitive characters. This causes the issue where the original format contain regex sensitive characters such as '.' and hence invalid values gets parsed with invalid formats.

1__ruby

As seen in the screenshot, The format '%d / %m / %y'(the one with slash as separator) should have been picked up, but instead it pickup '%d . %m . %y'(with dot separator) picked up because of '.' character which in regex means anything.

this ends up in invalid date.

Different structure of params in Rails 5

It's that time again: A new Rails release is around the corner, bearing the usual breaking changes.

In Rails 5.0.0.rc1 nested parameter hashes are no longer of type Hash but ActionController::Parameters.

Consider this typical params hash:

{ id: 1, action: 'update', controller: 'articles', article: { title: 'New release' } }

In Rails 4.2.6:

params.class == ActionController::Parameters
params[:article].class == Hash

In Rails 5.0.0.rc1

params.class == ActionController::Parameters
params[:article].class == ActionController::Parameters

There are two locations where delocalize assumes the nested params are instances of Hash which now also have to check for ActionController::Parameters. Unfortunately ActionController::Parameters is not defined in earlier versions of Rails, so the code is a little more involved.

Thoughts, ideas, suggestions?

@clemens Would you accept a pull request for this or do you already have something different in mind?

Test failure with Rails version >= 3.2.9

$ rake

Started
..........................FF.........
Finished in 0.375821 seconds.

  1) Failure:
test_dirty_attributes_must_detect_changes_in_decimal_columns(DelocalizeActiveRecordTest) [/Users/danieltamiosso/Development/danieltamiosso/delocalize/test/delocalize_test.rb:175]:
Failed assertion, no message given.

  2) Failure:
test_dirty_attributes_must_detect_changes_in_float_columns(DelocalizeActiveRecordTest) [/Users/danieltamiosso/Development/danieltamiosso/delocalize/test/delocalize_test.rb:182]:
Failed assertion, no message given.

37 tests, 50 assertions, 2 failures, 0 errors, 0 skips

probable error in methods "clone" and "dup"

I use the gem delocalize and Mongoid with rails 3.2.11.

It works very well.

However using the method clone or dup with attributes that use delocalize the dates back one day and loses the decimal number.

example:

class Parcel 
   include Mongoid::Document
   include Mongoid::Timestamps
   include Mongoid::MultiParameterAttributes
   include Delocalize::Delocalizable 

   field :description, type: String
   field :date_of_update, type: Date
   field :date_debt, type: Date
   field :original_value, type: BigDecimal

   delocalize date_of_update: :date, date_debt: :date
   delocalize original_value: :number
end
parcel = Parcel.new
parcel.date_of_update = (Time) 2007-10-01
parcel.date_debt = (Time) 2007-01-01
parcel.original_value = 1011.00

Cloning

new_parcel = parcel.clone

Result:

new_parcel.date_of_update  =>  (Time) 2007-09-30
new_parcel.date_debt =>  (Time) 2006-12-31
new_parcel.original_value = 101100

Using parcel.dup the same problem occurs.

Removing delocalize the clone function normally.

possible problem with parsing decimals?

Hi have an issue when updating a column which is declared as decimal(8,2), trying this both with mysql and postgres

| amount | decimal(8,2) | YES | | NULL | | <- mysql

amount | numeric(8,2) | <- postgres

the locale is "it" and i'm using ',' as the decimal separator and '.' as the delimiter

when i change, say, from 4,00 to 4,50, I see no update. if i change from 4,00 to 5,50 then I see the update query happening.

no clue what is happening. it happens both when using the app via browser and in console.

delocalize version is 0.3.1

Raise an exception when user submit an invalid date

Hello, I'm not sure it's a bug but the behavior is different than Rails. If we use a textfield to accept a date and user fills a invalid date like 31/06/2010 ( 31 june 2010 ) it will raise an exception in Delocalize datetime parse.

Right now my work around to avoid show a 500 error is validate the date with a date parse. Rails default behavior doesn't raise an exception but write an unexpected value to the property.

What do you think? Delocalize should use the same behavior of Rails or the exception is the wanted behavior? Thanks.

default in activerecord breaks ui

Hello, I found a serious bug. When the database already have a default in migration for the column delocalize return the wrong value.

For example:
t.decimal :value, :default => 0, :precision => 20, :scale => 2

Result in a textfield with filled with 0.0 instead of 0,00 if we have a local setted for it.

Writing a Time field and Accounting for DST

The delocalize is a great gem. I am surprised its functionality is not a default part of rails.

I have encountered an issue when writing a time to my postgres database and the time_zone. I have form where a user can input their opening/starting and closing/ending time for each day of a seven day week. When the user submits the form and stores the time in a time form in the database.

Here's the params passed by the edit view (US Eastern time zone set)

... "sched_mon_start"=>" 8:30 AM", ...

And heres the log of rails inserts into the database.

... SET "sched_mon_start" = '2013-04-25 12:30:00.000000', ...

And this is how the time is stored in the database like so

sched_mon_start: 2000-01-01 12:30:00 UTC

The problem is today (April 25), the East coast is UTC -4 but in January it is UTC -5. So the view shows up as an hour earlier. Also, when a user cycles between edit/save/show/edit/save/show the times crawl back one hour each commit.

Is there a fix for this that I am overlooking? Can I turn off the delocalize gem for these inputs?

I am using this with simple_form and here's my en.yml:

 time:
    input:
      formats: 
        - :default
        - :long
        - :short
        - :time
        - :date
    formats:
      default: "%m/%d/%Y %I:%M%p"
      short: "%B %e %I:%M %p"
      long: "%A, %B %e, %Y %I:%M%p"
      time: "%l:%M%p"
      date: "%m/%d/%Y"
    pm: PM
    am: AM

Test failure with Ruby 1.9

/usr/bin/ruby19 -I"lib:lib:test" -I"/usr/lib64/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib" "/usr/lib64/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader.rb" "test/delocalize_test.rb" 
Run options: 

# Running tests:

...................F...F..........

Finished tests in 0.409252s, 83.0784 tests/s, 114.8436 assertions/s.

  1) Failure:
test_delocalizes_localized_date_without_year(DelocalizeActiveRecordTest) [/media/repos/flame/git/delocalize/test/delocalize_test.rb:53]:
<Mon, 19 Oct 2009> expected but was
<Fri, 19 Oct 2012>.

  2) Failure:
test_delocalizes_localized_time_(non-DST)(DelocalizeActiveRecordTest) [/media/repos/flame/git/delocalize/test/delocalize_test.rb:86]:
<Sun, 01 Mar 2009 08:00:00 CET +01:00> expected but was
<Tue, 28 Feb 2012 08:00:00 CET +01:00>.

34 tests, 47 assertions, 2 failures, 0 errors, 0 skips
rake aborted!
Command failed with status (2): [/usr/bin/ruby19 -I"lib:lib:test" -I"/usr/l...]

Tasks: TOP => test
(See full trace by running task with --trace)

dirty attributes are not correctly set

I have the database field quantity with value 5.60 (english notation), which is presented in the view as 5,60.
If a user types in "5,60", it perfectly gets translated to 5.60.
If a user types in "5.60", it also gets perfectly translated, this time to 560. But the problem is, that the dirty attributes are not set: quantity_changed? is false and quantity_was is 560

Rails 3.2.22.2 app fails to start: uninitialized constant Delocalize::DelocalizableParameters

Steps to reproduce:

  • Take a working Rails 3.2.22.2 app.
  • Add gem 'delocalize', '1.0.0' to Gemfile and bundle.
  • Reload app.
  • Expected: app boots as normal. Actual:
NameError: uninitialized constant Delocalize::DelocalizableParameters
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/delocalize-1.0.0/lib/delocalize/railtie.rb:10:in `block (2 levels) in <class:Railtie>'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activesupport-3.2.22.2/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activesupport-3.2.22.2/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activesupport-3.2.22.2/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activesupport-3.2.22.2/lib/active_support/lazy_load_hooks.rb:25:in `each'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activesupport-3.2.22.2/lib/active_support/lazy_load_hooks.rb:25:in `on_load'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/delocalize-1.0.0/lib/delocalize/railtie.rb:4:in `block in <class:Railtie>'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/initializable.rb:30:in `instance_exec'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/initializable.rb:30:in `run'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/initializable.rb:55:in `block in run_initializers'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/initializable.rb:54:in `each'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/initializable.rb:54:in `run_initializers'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/application.rb:136:in `initialize!'
~/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/railties-3.2.22.2/lib/rails/railtie/configurable.rb:30:in `method_missing'
~/path/to/my/app/config/environment.rb:5:in `<top (required)>'
~/.rbenv/versions/2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
~/.rbenv/versions/2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
~/path/to/my/app/config.ru:8:in `block in <main>'
~/Library/Application Support/Pow/Versions/0.5.0/node_modules/nack/lib/nack/builder.rb:4:in `instance_eval'
~/Library/Application Support/Pow/Versions/0.5.0/node_modules/nack/lib/nack/builder.rb:4:in `initialize'
~/path/to/my/app/config.ru:1:in `new'
~/path/to/my/app/config.ru:1:in `<main>'

I was able to solve this by adding this line to the top of lib/delocalize.rb:

require 'delocalize/delocalizable_parameters'

Gemfile is missing from .gem file

This causes the tests not to be executable from within the gem; it would be nice to have the Gemfile there as well so that they can be executed fine.

Invalid number defaults to 0?

Hi Clemens,

First of all, congratulations. I really liked your approach on this solution.

I was testing the gem and I noticed that when I fill a number form field (validated by vlidates_numericatily_of) with "abc" instead of getting a invalid number format error, the field gets set to 0 and the model gets saved.

Did you get to this situation already? Am I missing something?

I pushed a test app showing the issue in this link.

http://github.com/mhfs/delocalize_test

Thanks!

Not updating attribute on ocasion

Hi, I've been using this great gem for a couple of days and I believe I've found a bug:

I've created a new rails app to try to isolate the bug, and I've been successfull:

Currency model migration:
create_table :currencies do |t|
t.decimal :value, :precision => 12, :scale => 2

    t.timestamps
  end

Environment:

config.gem "delocalize"
config.i18n.default_locale = 'pt-BR'

locales/pt-BR.yml:

pt-BR:
  number:
    format:
      separator: ","
      delimiter: .
      precision: 3

Now, on script/console:

http://gist.github.com/263347

Since no changes are detected, the record won't be saved.

The funny thing is: if you set the value to the same string twice, the changes are detected:

http://gist.github.com/263348

Any insights?

Delocalize in Production

Delocalize continues to work well for me in production.

I am using Delocalize on a date column with my yaml configured like so:

  date:
    input:
      formats:
        - :default
        - :long
        - :short
    formats:
      default: ! '%d/%m/%Y'
      long:    ! '%B %d, %Y'
      short:   ! '%b %d'
    placeholder:
      default: 'dd/mm/yyyy'

I am using simple_form and I am initializing the input like so:

      <%= f.input :birth_date, 
          as:'string', 
          label:"DOB", 
          input_html: {include_blank:true, 
            value: date_format(f.object.birth_date), 
            class: "datepicker",
            placeholder: ( t 'date.placeholder.default' )} %>

Number parser failing with i18n fallbacks

This is the same as #44. Here's a fix:

diff --git a/lib/delocalize/parsers/number.rb b/lib/delocalize/parsers/number.rb
index dc66eb9..bd2715c 100644
--- a/lib/delocalize/parsers/number.rb
+++ b/lib/delocalize/parsers/number.rb
@@ -7,7 +7,8 @@ class Number
       def parse(value)
         return value unless value.is_a?(String)

-        separator, delimiter = I18n.t([:separator, :delimiter], :scope => :'number.format')
+        separator = I18n.t(:separator, :scope => :'number.format')
+        delimiter = I18n.t(:delimiter, :scope => :'number.format')
         value.gsub(delimiter, '').gsub(separator, '.')
       end
     end

Delocalize does not work with Gem best_in_place

Best_in_place is "The Unobtrusive in Place editing solution".

But it it doesn't work smoothly with delocalize.
When editing a field, the value is not delocalized.

E.g. editing a field with value 2.5 should show "2,5" with locale de, but it shows "2.5".
I also filed an issue at the best_in_place Gem, as I can't estimate where the source of the problem lays.
bernat/best_in_place#276

Set Date::DATE_FORMATS[:default]

Delocalize acts only upon forms:

<%= text_field :model, :created %> shows 27/08/2010 (pt-BR)
<%= @model.cerated %> shows 2010-08-27 :(

Setting Time::DATE_FORMATS[:default] and Date::DATE_FORMATS[:default] should fix this issue

The gemspec references files not in the repo

This prevents bundler from installing bins or native extensions, but that may not affect its functionality.
The validation message from Rubygems was:
["test/rails3_app/config/initializers/new_rails_defaults.rb", "test/rails3_app/config/initializers/session_store.rb", "test/rails3_app/config/routes.rb"] are not files

Value not delocalized if errors present on attribute

(Spike branch)

Delocalize skips delocalization for attributes with errors (https://github.com/clemens/delocalize/blob/spike/lib/delocalize/action_view.rb#L24).

In my case there are date fields with a conditional range validation that is deactivated by default. So I can enter any date value and save the record successfully. However, the conditional validation may be triggered later on – and now the already saved value could suddenly become invalid (because it’s outside the range). When I display the edit form at this stage, the date field is not delocalized.

Fixing this would require to remove the line mentioned above and instead add a rescue clause or a type check around the call to I18n.l in line 36 (number_to_precision in line 34 needs no change as it just returns its argument if it can’t be converted to a number).

Should I prepare a pull request? Or is this use case too obscure to justify the added complexity?

thousand problem

the gem fails to convert a number when it is a invalid thousand, for example

R$ 10.23, will generate 1.023, that's because it is missing to test if it is a valid thousand.
In this situation the user typed a wrong value, it should be R$ 10,23 instead of R$ 10.23, however the gem should not convert it to R$ 1.023, shouldn't it raise an exception or give an error???

rails g fails - 0.3.1

When pulling up help with $rails g using delocalize-0.3.1, fails.
Using:

  • ruby 2.0.0-p247
  • rails 4.0.0
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/delocalize-0.3.1/lib/delocalize/rails_ext/action_view.rb:6:in `<top (required)>': uninitialized constant ActionView::Helpers::InstanceTag (NameError)
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/delocalize-0.3.1/lib/delocalize/railtie.rb:9:in `block (2 levels) in <class:Railtie>'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `instance_eval'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `execute_hook'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:28:in `block in on_load'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:27:in `each'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:27:in `on_load'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/delocalize-0.3.1/lib/delocalize/railtie.rb:8:in `block in <class:Railtie>'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `instance_exec'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `run'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:180:in `each'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'
    from /home/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:54:in `run_initializers'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:215:in `initialize!'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /home/user/Projects/the_quiz_project/question_what/config/environment.rb:5:in `<top (required)>'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:189:in `require'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:189:in `require_environment!'
    from /home/user/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands.rb:45:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

Rails 4.0 support

Currently Delocalize does not work with Rails 4.0 (beta1).

After some code browsing it looks like the convert_number_column_value has been moved into the Column class of the connection adapter.

Also the to_input_field_tag method has been refactored and is no longer available.

Gem release.

I have a rails 3.1 project running with (MRI)1.9.2 using delocalize.

When using the rubygems release, with JRuby 1.6.4(on 1.8 mode), I'm getting some datetime conversion errors, but when I configure my Gemfile to lookup at the git repo, it just works perfectly.

Can we have a new gem release?

Thanks in advance.

YML

I got everything working fine on my local development (os x with rvm Ruby 1.9.2) but had issues running on my dev server (Ubuntu 11.04 rvm Ruby 1.9.2). Found out it was an issue with the yml format and Psych not being able to handle the syntax from the example given in the readme.

Error message from logs:

Psych::SyntaxError (couldn't parse YAML at line x column y):

References:

The solution can be found here: http://stackoverflow.com/questions/4980877/rails-error-couldnt-parse-yaml#answer-5323060

http://pivotallabs.com/users/mkocher/blog/articles/1692-yaml-psych-and-ruby-1-9-2-p180-here-there-be-dragons

Pull request coming soon with updated syntax...

Hidden field and select values changed to zero

I have a form with multiple hidden fields and selects with numeric values. After installing delocalize al numeric values within these two types of inputs get converted to zero.

Also if the numeric hidden field is a decimal, the action_view extension was throwing a error:

  • wrong argument type nil (expected Fixnum)

The Trace:
actionpack (3.0.4) lib/action_view/helpers/number_helper.rb:281:in round' actionpack (3.0.4) lib/action_view/helpers/number_helper.rb:281:innumber_with_precision'
delocalize (0.2.5) lib/delocalize/rails_ext/action_view.rb:30:in `to_input_field_tag'

I temporarily fixed this by not formatting the number when its hidden (the default behavior was to not formatted only if its hidden and it was a integer, but in my case the hidden field value was a decimal)

I would like to disable all numeric localization, is there a way to do that?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.