Skip to content

FIX: Enumerize::Value to handle callable i18n_scope dynamically #463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions lib/enumerize/value.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,22 @@ def initialize(attr, name, value=nil)

super(name.to_s)

@i18n_keys = @attr.i18n_scopes.map do |s|
@default_i18n_keys = []
@default_i18n_keys << :"enumerize.defaults.#{@attr.name}.#{self}"
@default_i18n_keys << :"enumerize.#{@attr.name}.#{self}"
@default_i18n_keys << ActiveSupport::Inflector.humanize(ActiveSupport::Inflector.underscore(self)) # humanize value if there are no translations
end

def i18n_keys
@attr.i18n_scopes.map do |s|
scope = Utils.call_if_callable(s, @value)

:"#{scope}.#{self}"
end
@i18n_keys << :"enumerize.defaults.#{@attr.name}.#{self}"
@i18n_keys << :"enumerize.#{@attr.name}.#{self}"
@i18n_keys << ActiveSupport::Inflector.humanize(ActiveSupport::Inflector.underscore(self)) # humanize value if there are no translations
@i18n_keys
end.push(*@default_i18n_keys)
end

def text
I18n.t(@i18n_keys[0], :default => @i18n_keys[1..-1]) if @i18n_keys
I18n.t(i18n_keys[0], :default => i18n_keys[1..-1])
end

def ==(other)
Expand Down
31 changes: 31 additions & 0 deletions test/value_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,37 @@ def value?(value)
expect(val.text).must_be :==, "Scope specific translation"
end
end

context 'allows to pass a proc as i18n_scopes param with dynamic scope' do
let(:translations) do
[:en, :other => {:scope => {:"foo" => {:test_value => "Foo translation"}, :"bar" => {:test_value => "Bar translation"}}}]
end

before do
@value = nil
attr.i18n_scopes = [proc { "other.scope.#{@value}" }, :"other.scope.foo"]
end

it 'returns default with nil value' do
store_translations(translations) do
expect(val.text).must_be :==, "Foo translation"
end
end

it 'returns foo translation with foo value' do
store_translations(translations) do
@value = "foo"
expect(val.text).must_be :==, "Foo translation"
end
end

it 'returns bar translation with bar value' do
store_translations(translations) do
@value = "bar"
expect(val.text).must_be :==, "Bar translation"
end
end
end
end

describe 'boolean methods comparison' do
Expand Down