Overriding Rails Error (Validation) Messages from Gems/Plugins -


is there accepted way of overriding error (validation) messages gem/plugin in rails?

for example, i'm using activemerchant gem, , if puts in american express credit card number, selects 'mastercard', not-very-descriptive "type not correct card type" error.

i can around doing this:

def validate_card   unless credit_card.valid?     credit_card.errors.full_messages.each |message|       if message =~ /is not correct card type/i         errors.add_to_base "this credit card number invalid.                              please ensure selected correct type."       else         errors.add_to_base message       end     end   end end 

but technique becomes unmaintainable , (at least in opinion) far 'best-practices'.

similarly, unpack activemerchant gem , hack put in own custom error messages, seems unmaintainable require same hacks added future, unpacked, versions of activemerchant.

in honesty, you're best bet either rewrite parts of gem/plugin suit needs. unfortunately if decide update gem/plugin @ time lose changes.

however, ruby dynamic language, classes can reopened, , can override methods of module/class file. through magic of open source, i've tracked down module/class/method you'd need meddle achieve goal.

put following in file , ensure gets loaded after activemerchant (how load dependent on whether you're using plugin or gem)

module activemerchant   module billing     class creditcard        private       def validate_card_number #:nodoc:         errors.add_to_base "this credit card number invalid. \n" +          "please ensure selected correct type." unless              creditcard.valid_number?(number)       end     end   end end 

n.b.: method relies on activemerchant internals, bad idea. see lesser of 2 evils maintaing own version of activemerchant. should update gem/plugin , above code relies on has changed, break in odd ways.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -