Forum: Ruby on Rails Putting Some Logic in Accessors That Get DB Field Data

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
John K. (Guest)
on 2007-01-25 19:45
(Received via mailing list)
Wow... I have no clue how to explain this.  Excuse my vocabulary.

Their is one field in my DB that I want to test if it is null before
someone accesses it and if it is null return zero.  How to I overwrite
the accessor for a field in my model so that I can test the value
being returned and if it is null return zero, otherwise return what
the value is?

Why am I doing this?  Because unfortunately the data I am accessing is
from legacy systems so I can't make sure that all the information has
been cleaned up before hand!  Plus the bozzo who is writing the tool
to populate my DB from legacy systems refuses to clean data before he
puts it into my DB!  Garbage in... garbage out! :-)

Am I making sense?  How would I better describe what I am trying to do?

Thanks peeps :-)

John

--
John K.
removed_email_address@domain.invalid

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info
Jim L. (Guest)
on 2007-01-25 20:38
(Received via mailing list)
> Their is one field in my DB that I want to test if it is null before
> someone accesses it and if it is null return zero.  How to I overwrite
> the accessor for a field in my model so that I can test the value
> being returned and if it is null return zero, otherwise return what
> the value is?

In your model, create a method with the same name as the attribute.
This overwrites the automagical one made by AR.

def my_attr
  if @my_attr.nil?
    0
  else
    @my_attr
  end
end

@my_attr is still populated by Active Record, but you're now
controlling what happens when it's retrieved outside the model.

You can also overwrite the assignment by making a method like

def my_attr=(value)
  if value.nil?
    @my_attr = 0
 else
    @my_attr = value
  end
end

The equal sign in the method definition denotes it's the method for
assignment.
John K. (Guest)
on 2007-01-25 21:21
(Received via mailing list)
Sexy! :-)

On 1/25/07, Jim L. <removed_email_address@domain.invalid> wrote:
> def my_attr
> You can also overwrite the assignment by making a method like
>
> >
>


--
John K.
removed_email_address@domain.invalid

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info
This topic is locked and can not be replied to.