yaroslav / russian Goto Github PK
View Code? Open in Web Editor NEWRussian language support for Ruby and Rails | Поддержка русского языка для Ruby и Rails
License: MIT License
Russian language support for Ruby and Rails | Поддержка русского языка для Ruby и Rails
License: MIT License
You are passing a block expecting two parameters,
so the old hash behavior is simulated. As this is deprecated,
this will result in an ArgumentError in Rails 7.0.
(called from full_messages at /app/vendor/ruby/3.0.0/bundler/gems/russian-630526b320f9/lib/russian/active_model_ext/custom_error_message.rb:45)
Первая часть правильно закодирована в юникод, вторая в ASCII.
Вот, как выглядит строка в браузере
Вс, 05 июля 2009, 10:07:46 ���������� ����� (����)
HTML
Р’СЃ, 05 июля 2009, 10:07:46 Московское время (лето)
Всем привет, подскажите как избавиться от склонения месяца в
l(Time.now, :format => "%d %B %Y %H:%m")
отдает
23 апреля 2010 21:04
, а хочу
23 Апрель 2010 21:40
заранее спасибо
localize
should take four arguments instead of three
strftime не работает с месяцами, которые пишутся капсом, например при параметре %^B (месяц капсом)
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
Russian::strftime(Time.now, "%d %B")
Russian::strftime(Time.now, "%-d %B")
должно быть 1 сентября?
пока пользуюсь %e %B но это не совсем то.
$KCODE
in lib/russian.rb
issues warning "variable $KCODE is no longer effective; ignored" in Ruby 1.9.1 and should be wrapped in if/end
:
if RUBY_VERSION < "1.9"
$KCODE = 'u'
end
bundle install Using russian (0.2.7) from git://github.com/yaroslav/russian.git (at master) russian at /home/kir/.rvm/gems/ruby-1.9.2-p136/bundler/gems/russian-57af7fee22f9 did not have a valid gemspec. This prevents bundler from installing bins or native extensions, but that may not affect its functionality. The validation message from Rubygems was: ["lib/vendor/i18n_label", "lib/vendor/i18n_label/init.rb", "lib/vendor/i18n_label/install.rb", "lib/vendor/i18n_label/lib", "lib/vendor/i18n_label/lib/i18n_label.rb", "lib/vendor/i18n_label/Rakefile", "lib/vendor/i18n_label/README.textile", "lib/vendor/i18n_label/spec", "lib/vendor/i18n_label/spec/i18n_label_spec.rb", "lib/vendor/i18n_label/spec/spec_helper.rb", "lib/vendor/i18n_label/tasks", "lib/vendor/i18n_label/tasks/i18n_label_tasks.rake", "lib/vendor/i18n_label/uninstall.rb"] are not files
2.2.1 :002 > Russian::strftime(Date.new(2015,12,31), "%d %B %Y" )
=> "31 декабря 2015"
2.2.1 :003 > Date.parse(Russian::strftime(Date.new(2015,12,31), "%d %B %Y" ))
=> Fri, 31 Jul 2015
2.2.1 :007 > Russian::strftime(Date.new(2015,06,30), "%d %B %Y" )
=> "30 июня 2015"
2.2.1 :008 > Date.parse(Russian::strftime(Date.new(2015,06,30), "%d %B %Y" ))
=> Thu, 30 Jul 2015
In this commit -- https://rails.lighthouseapp.com/projects/8994/tickets/3266/a/279465/add_almost_to_distance_of_time_in_words.diff was added new string which are missing in current version russian from git.
Если в формате задать "%^B", то вместо русского названия месяца прописными буквами выведется название месяца по-английски (тоже прописными буквами).
Возможно стоит релизнуть 0.6.1?
Имеется проблема с russian 0.6:
Russian.strftime Date.today, "%B" #=> "марта"
В предыдущих версиях (проверил 0.2.7) было:
Russian.strftime Date.today, "%B" #=> ""Март""
сабж
1.9.3-p362 :047 > Russian::l(Time.now + 2.day, :format => '%-d %B')
=> "1 Февраль"
1.9.3-p362 :048 > Russian::l(Time.now + 2.day, :format => '%d %B')
=> "01 февраля"
1.9.3-p362 :001 > Russian::l(Time.now + 2.day, :format => '%1d %B')
=> "1 Февраль"
1.9.3-p362 :002 > Russian::l(Time.now + 2.day, :format => '%2d %B')
=> "01 Февраль"
Using russian (0.6.0)
anton@ubuntu:/work/tradein$ rails -v/work/tradein$ ruby -v
ruby -Rails 3.2.11
anton@ubuntu:
ruby 1.9.3p362 (2012-12-25 revision 38607) [i686-linux]
спеки это место проходят отлично
когда уже ? ;)
For ruby 3.0 support:
https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/
Params to I18n should be passed this way:
def translate(key, options = {})
I18n.translate(key, **options.merge({ :locale => LOCALE }))
end
def localize(object, options = {})
I18n.localize(object, **options.merge({ :locale => LOCALE }))
end
Доброго времени суток,
Прикручиваю russian к Redmine. При активации gem'а столкнулся с исключением:
Файл переводов содержит:
label_x_open_issues_abbr_on_total:
zero: 0 открыто / {{total}}
one: 1 открыт / {{total}}
other: "{{count}} открыто / {{total}}"
Исключение:
translation data {:other=>"{{count}} открыто / {{total}}", :zero=>"0 открыто / {{total}}", :one=>"1 открыт / {{total}}"} can not be used with :count => 8
Backtrace:
gems/russian-0.2.5/lib/russian/backend/advanced.rb:118:in pluralize' gems/activesupport-2.3.5/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb:40:in
translate'
gems/activesupport-2.3.5/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb:165:in t' redmine/lib/redmine/i18n.rb:13:in
l'
Пройдясь отладчиком, обнаружил, что в вызове pluralize используется locale_pluralize и key превращается в :many. Без russian всё работает.
Пример:
Russian::transliterate('Я спросил у ясеня') => YA sprosil u yasenya
на мой взгляд логичнее было бы Ya sprosil u yasenya
Мне кажется не очень красиво заменять твердый знак дефисом в методе parameterize:
"съедобный подъезд".parameterize #=> "s-edobnyy-pod-ezd"
Визуально в этом примере из двух слов мы получили четыре.
Понятно, что это идет из транслитерации, где твердый знак превращается в одиночную кавычку-апостроф, которая затем превращается в дефис:
Russian.transliterate "съедобный подъезд" #=> "s'edobnyy pod'ezd"
"s'edobnyy pod'ezd".parameterize
Можно попробовать заменять твердый знак на y или j:
"съедобный подъезд".parameterize #=> "syedobnyy-podyezd"
"съедобный подъезд".parameterize #=> "sjedobnyy-podjezd"
Код иннициализации:
translations = {}
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::KeyValue.new(translations), I18n.backend)
if Rails.configuration.appa[:i18n].present? then
Rails.configuration.appa[:i18n].each do |locale, h|
I18n.backend.store_translations(locale, h, :escape => false)
end
end
Вываливается здесь:
() Users/yuri/.rvm/gems/ruby-2.1.1/bundler/gems/russian-6da1fe45cbff/lib/russian/action_view_ext/helpers/date_helper.rb
# строка 101
if I18n.backend.send(:lookup, I18n.locale, :'date.common_month_names')
с NotImplementedError в lookup i18n (0.6.9) lib/i18n/backend/base.rb
Приватный метод lookup не оверрайдится в Chain, по-моему в этом месте вместо send(...) уместнее было бы использовать I18n.t(:'date.common_month_names')
В Rails i18n guides сказано:
If the lookup for the key does not return a Hash suitable for pluralization,
an 18n::InvalidPluralizationData exception is raised.
Похоже, я наткнулся как раз на такой случай:
translation data {:one=>"1 ошибка не позволяет сохранить запись в базе",
:other=>"%{count} ошибок не позволяют сохранить запись в базе"}
can not be used with :count => 8
Было бы здорово добавить в документацию, с какими ключами нужно описывать варианты плюрализации фразы в locales/ru.yml (в смысле, :one, :other и т.п.)
Модели:
Address: has_many :delivery_settings, :through => :delivery_address
DeliverySetting: has_many :addresses, :through => :delivery_addresses
DeliveryAddress: belongs_to :delivery_setting, belongs_to :address, validates_uniqueness_of :address_id, :scope => :delivery_setting_id
При попытке добавить вторую связь (которая не проходит валидацию):
can't convert ActiveRecord::Error into String
vendor/plugins/russian/lib/russian/active_record_ext/custom_error_message.rb:47:in `+'
@errors выглядят так:
{"address_id"=>[#<ActiveRecord::Error:0x26d39e8 @type=:taken, @message=:taken, @options={:value=>6}, @Attribute=:address_id, @base=#<DeliveryAddress id: nil, address_id: 6, delivery_setting_id: 4>>]}
This code in template
<%= f.label :user_type, 'физическое лицо', :value => 'phys' %>
When gem russian 0.2.7 is on render to:
<label for="user_user_type" value="phys">phys</label>
And when gem is off:
<label for="user_user_type_phys">phys</label>
%b интерпретируется, как %B.
То есть <%= l news_item.created_at, :format => "%d %b %Y" %> выведит "25 июля 2012".
Версия рельсов 3.2.1
Прежде всего - спасибо за отличную работу! Очень помогает при разработке.
Вопрос такой - возможно ли изменить регистр букв? Обычные рельсовые методы не работают с кирилицей (upcase, capitalize, etc.)
Планируется ли поддержка этой фичи?
Russian::transliterate("Дональд\nКнут")
=> "DonaldKnut"
config.gem 'yaroslav-russian', :lib => 'russian', :source => 'http://gems.github.com'
В системе установлен i18n-0.3.5 как просили для rails 3
после чего слетела локализация дат
I18n.l(Time.now)
ArgumentError: wrong number of arguments (4 for 3)
from /usr/lib/ruby-enterprise-1.8.7/lib/ruby/gems/1.8/gems/i18n-0.3.5/lib/i18n.rb:224:inlocalize' from /usr/lib/ruby-enterprise-1.8.7/lib/ruby/gems/1.8/gems/i18n-0.3.5/lib/i18n.rb:224:in
l'
Всем еще раз привет. На этот раз такой вопрос. А есть ли какой-то медот обратный localize?
Russian::strftime(date, "%B") согласно документации должна выдать standalone month, однако выдает как при обычной дате, допустим - мая, апреля, января.
russian-0.6.0
После установки свежей 0.6.0 версии возникает проблема при использовании en локали.
I18n::InvalidPluralizationData in Library_folders#show
translation data {:other=>"%{count} months", :one=>"1 month"} can not be used with :count => 2
Код
time_ago_in_words(file.upload_date)
При использовании русской локали проблемы нет. Также проблема НЕ возникает если использовать форк git://github.com/kelvich/russian.git
ruby 1.8.7
rails 3.1.1
actionpack (3.1.1)
Rails 4.1.0
Devise 3.2.4
Devise adds this for validatable model:
# https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb#L34
validates_confirmation_of :password, if: :password_required?
Rails confirmation helper works like that:
# https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations/confirmation.rb#L13
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
Russian translation is:
# https://github.com/yaroslav/russian/blob/master/lib/russian/locale/activerecord.yml#L22
confirmation: "не совпадает с подтверждением"
So we end with Password confirmation не совпадает с подтверждением
.
PS:
The default confirmation translation is:
# https://github.com/rails/rails/blob/3b68a422231ca579b8ebcd93c561810c25674c49/activemodel/lib/active_model/locale/en.yml#L12
confirmation: "doesn't match %{attribute}"
so we get Password confirmation doesn't match Password
.
PPS:
I suggest to use e.g.
confirmation: "и %{attribute} не совпадают"
Should I make a PR?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.