Skip to content

Commit

Permalink
Added some kind of odd support for i18n interpolation in the custom :…
Browse files Browse the repository at this point in the history
…message messages for the live validations. E.g. :message => "but srsly, {{model}}" will be translated and used as "but srsly, Post" in the live validations.
  • Loading branch information
augustl committed Mar 20, 2009
1 parent f3e9757 commit 960cbb2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/live_validations/adapter/validation_hook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,15 @@ def setup
# Returns a user specified validatior error message, or falls back to the default
# I18n error message for the passed key.
def message_for(key)
callback.options[:message] || I18n.translate('activerecord.errors.messages')[key]
handwritten_message || I18n.translate('activerecord.errors.messages')[key]
end

def handwritten_message
return unless callback.options[:message]

I18n.backend.send(:interpolate, I18n.locale, callback.options[:message], {
:model => adapter_instance.active_record_instance.class.human_name
})
end

# Returns the string that the validator should use as a regex in the javascripts.
Expand Down
11 changes: 10 additions & 1 deletion test/general_adapter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,19 @@ def teardown
end

def test_message_for_with_custom_message
@hook.expects(:callback).returns(OpenStruct.new(:options => {:message => "Yep!"}))
@hook.expects(:callback).at_least_once.returns(OpenStruct.new(:options => {:message => "Yep!"}))
@hook.expects(:adapter_instance).returns(OpenStruct.new(:active_record_instance => @post))

assert_equal "Yep!", @hook.message_for(:blank)
end

def test_message_for_with_l18n_fancy_message
@hook.expects(:callback).at_least_once.returns(OpenStruct.new(:options => {:message => "The {{model}}"}))
@hook.expects(:adapter_instance).returns(OpenStruct.new(:active_record_instance => @post))

assert_equal "The Post", @hook.message_for(:blank)
end

def test_message_for_without_custom_message
@hook.expects(:callback).returns(OpenStruct.new(:options => {}))
assert_equal I18n.translate('activerecord.errors.messages')[:blank], @hook.message_for(:blank)
Expand Down

0 comments on commit 960cbb2

Please sign in to comment.