Rails legacy app and Ruby 2 error: can not load tr

2019-05-03 10:45发布

问题:

I have a legacy Rails application which I want to upgrade to recent Rails and Ruby versions.To start with I am trying to setup the application with Ruby 2.1.2

$ rails -v
Rails 2.3.18

$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [i686-linux]

When I tried to run the rake task rake db:schema:load RAILS_ENV=test I encountered following error

 can not load translations from /activesupport-2.3.18/lib/active_support/locale/en.yml, the file type yml is not known

Searching through Google I found the following reference https://github.com/rails/rails/issues/10514 which mentioned that there is incompatibility between Rails 2.3 and Ruby 2+ versions.

Can anybody please help me applying a monkey-patch mentioned about in the reference link?

Thanks, Jignesh

回答1:

Finally resolved the error

 can not load translations from /activesupport-2.3.18/lib/active_support/locale/en.yml, the file type yml is not known

by monkey-patching the Rails’s I18n::Backend::Base#load_file(filename) method.

The solution is as follows:

1.1 Created a file named ruby2.rb at /config/initializers

1.2 Added following contents to /config/initializers/ruby2.rb

  if Rails::VERSION::MAJOR == 2 && RUBY_VERSION >= '2.0.0'
    module I18n
      module Backend
        module Base
          def load_file(filename)
            type = File.extname(filename).tr('.', '').downcase
            # As a fix added second argument as true to respond_to? method
            raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
            data = send(:"load_#{type}", filename) # TODO raise a meaningful exception if this does not yield a Hash
            data.each { |locale, d| store_translations(locale, d) }
          end
        end
      end
    end
  end

1.3 Finally ran

   $ rake db:schema:load RAILS_ENV=test

and the schema was successfully loaded.

Most helpful references I could find and which helped me get to the solution:

  1. https://github.com/rails/rails/issues/10514
  2. https://www.lucascaton.com.br/2014/02/28/have-a-rails-2-app-you-can-run-it-on-the-newest-ruby/