How do I automatically modify a method when accessing it?

I’m in a weird situation where I’m storing encrypted information in a
database. For example, a field would be stored in its
encrypted format, so its not human-readable when accessing:
=> “)@Nw0asna;sd//20b3Q#A02nsoasd \n”

(This is just an example. I’m not actually encrypting names and the
model isn’t User :wink: But you get the idea.)

What I’m trying to figure out is the right way to go about
automatically assigning the “name” method to decrypt the data itself
when it’s being pulled out for display.

For example, I tried:

def name = decrypt_name

def decrypt_name

However, that has obvious problems - in my test, it seems to form an
infinite loop, bouncing back and forth between the “name” method and
the decrypt_name method (because one calls the other).

Is there any way other than writing specific get and set methods to do
this? I’d even be happy with a retrieval happening within find:

=> #<User id: 1, name: “John D.”>

Even though “name” stored inside the database is actually encrypted.

Any thoughts? Thanks :slight_smile:

Okay, I think I’m on the right track.

I just found out that ActiveRecord::Base has a section on overwriting
default accessors. So my basic method is now:

def name

The only thing that concerns me is that I also have a
before_save :encrypt_data call as part of the class definition. So
let’s say I submit a form via post:

@user =[:user])

If I read this right, when I call, or if I were to specify
User.find(:first, :conditions => {:name => “John D.”}), it would
first try to decrypt data that isn’t encrypted in the first place).

Am I way off track here or is this about right, and if so, is there
any way I can automate the abstraction that needs to take place, so
that, when accessed, is decrypted only if it’s in an
encrypted form?

Hope that makes sense :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs