Should we override model accessors?


#1

I have stumbled across an issue with FormHelper#text_field and thought
it was worth a patch. The ticket (with patch) is here

http://dev.rubyonrails.org/ticket/6908

It seems like my solution can’t be applied because the form helper
methods really needs to use the *_before_type_cast methods because
of numerical attributes. (By the way, the actionpack tests do not show
that yet)

The thing is that the problem hit something inside me and I got
thinking:
should we really try to override the default attribute accessors? I
mean,
there are .read and .write_attributes for those of us who want to, but
should we?

What I was originally trying to have was something like

def title
result = read_attribute(:title)
return title_from_name || PLACE_HOLDER_TITLE.t if result.nil? ||
result.empty?
return result
end

(Rough translation: in case there isn’t a title, generate a default one
based on the name)

But, because of the before_type_cast issue, I had to use something
along
these lines

def title; title_before_type_cast; end
def title_before_type_cast
result = read_attribute(:title)
return title_from_name || PLACE_HOLDER_TITLE.t if result.nil? ||
result.empty?
return result
end

…and that hurts. A lot! Not to mention that it may have introduced
some
subtle bugs that will come back to haunt me in the future.

I could also have tried renaming the db column to db_title or
something, but
that doesn’t seem right either. I thought about using something like
validates_*,
but this isn’t really a validation. We are just providing some sample
data that
would be tedious for the user to enter in many cases.

Is there any idiomatic solution for that?

Cheers,

Thiago A.