logo       

Re: Variable validation: msg#00786

lang.ruby.general

Subject: Re: Variable validation

Kent Dahl wrote:

> Chris Morris wrote:
>>
>> I've got a class that has a number of instance variables, some of which
>> must be set prior to calling a save function to write these off somewhere
>> else. I'm doing the following:
>>
>> def check_required
>> if @password == nil or @password.empty?
>> or @firstName == nil or @firstName.empty?
>> or @lastName == nil or @lastName.empty?
>> or @nickName == nil or @nickName.empty?
>> or @email == nil or @email.empty?
>> raise RequiredDataMissingError('')
>> end
>>
>> .. but this smells.
>
> If all these are accessible from the outside in reader methods, you
> could use an array of symbols and send:
>
> <CODE>
> class RequiredDataMissingError < Exception
> end
>
> class X
> MANDATORY_FIELDS = [ :password, :firstName, :lastName,
> :nickName, :email ]
>
> attr_accessor *MANDATORY_FIELDS
>
> def check_required
> if MANDATORY_FIELDS.find{|field|
> value = self.send(field)
> value == nil or value.empty?
> } then
> raise RequiredDataMissingError
> end
> end
> end
> </CODE>
>
> This does add a methodcall indirection, which could hurt you
> performancewise, but you seem to be (rightfully) trying to optimize for
> eyeball time :-)
>

Or perhaps:

class C
REQD = ['password', 'firstname', 'lastname'] #etc.

def check_required
missing = REQD.map {|r| (eval "@#{r}").to_s == '' ? nil : r}.compact
missing.empty? or raise "How 'bout these, punk? #{missing.join ', '}"
end
end

Or if you hate using eval, you can check instance_variables to see if your
field exists.
To check if it's '' though, you'd need eval, or store a mapping from the
variable name to
the value somewhere, or use an accessor method, or ... (?)

Another tip: If you're using constant strings as hash keys, I think it's
better style
and more efficient to use symbols instead: {:a => 1, :b => 2, :c => 3} instead
of {'a'
=> 1, 'b' => 2, 'c' => 3}. If you need the string value, you can use
Symbol#id2name
(aliased to Symbol#to_s) to convert it.



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise