Question

I have a fairly simple ruby syntax question (and a couple other clarifications), and I can't figure it out for the life of me.

The context is I have pretty common model class subclassing ActiveRecord::Base, and I am utilizing validates.

I believe Ruby convention likes keeping things neat by splitting long pieces of code across multiple lines if those lines go up to 80 lines unless it's something difficult to do that with like a regular expression. My first question is this:

How do I properly split up this validates line so it works properly?

validates :email, :uniqueness => true, :length => {:within => 5..50}, :format => {:with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i}

I have tried things like:

validates(
    :email,
    :uniqueness => true,
    :length => {:within => 5..50},
    :format => {:with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i}
)

I read in ruby convention somewhere that you could split lines using a backslash, and I haven't attempted it yet because I think that'd look a bit weird especially when you can utilize Ruby's power by just making sure a comma or operand is at the end of the line.

My final question is:

Could someone write this validates method with all the proper braces and brackets in place? Maybe I am a bit confused as to what basic syntax goes where.

Quick Recap:

How to split up single line validates above properly?
Can you split lines of ruby code with a backslash?
Someone write the same method written with all braces and brackets.

Thanks ahead of time.

Was it helpful?

Solution

You have the right idea. I would write the validates macro thusly,

validates :email,
  :uniqueness => true,
  :length => {:within => 5..50},
  :format => {:with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i}

We don't really need the enclosing brackets for a class macro. The first line would clearly indicate that we are validating the :email attribute, the subsequent lines are various validations on it.

Yes, you can use backslash, but it's generally un-needed and imo, looks ugly to me. Better to end on an operator and then continue the next line indented. see http://ruby-doc.org/docs/ProgrammingRuby/html/language.html for an example viz-a-viz

I would tend to keep RegExp literals all in one line if possible. If it get's too long, you can start using Regexp.new instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top