Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Rails AR. validate one field, with 4 validators & 2 condition block

validates :inn,
          presence: { if: -> { user.is_a?(Client) } },
          inn: { if: -> { user.is_a?(Client) } },
          uniqueness: { if: -> { user.is_a?(Client) } },
          absence: { if: -> { user.is_a?(Department) } }

Could I have some tips on refactoring this?

share|improve this question
2  
inn as an option of validates? –  tokland Dec 27 '13 at 13:44

2 Answers 2

up vote 1 down vote accepted

You can try something like this (obviously names can be shorter):

if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }
validates :inn, presence: if_user_is_a[Client], ..., absence: if_user_is_a[Department]

or

if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }
if_user_is_a_client = if_user_is_a[Client]
...
validates :inn, presence: if_user_is_a_client, ...
share|improve this answer
    
It seems better, but maybe is it something better than that? –  asiniy Jan 9 '14 at 5:34
    
It seems there isn't any better than that. Regards! –  asiniy Jan 21 '14 at 23:49

You can try to use a method instead of repeat yourself 4 times

Something like:

validates :inn,
          presence: { inn_meth { Client } },
          inn: { inn_meth { Client } },
          uniqueness: { inn_meth { Client} },
          absence: { inn_meth{ Department } }

def inn_meth
    if: -> { user.is_a?(yield) }
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.