alias_attribute
Wednesday, January 21st, 2009 · 0 comments
The jewel that is alias_attribute "allows you to make aliases for attributes, which includes getter, setter, and query methods". Observe how these 18 lines of code becomes 3.
def code
content
end
def code=(code)
self.content = code
end
def title
header
end
def title=(title)
self.header = title
end
def url
cite
end
def url=(url)
self.cite = url
end
This piece of code was taken from a tumblelog app I've been working on, it makes use of single-table-inheritance (STI) to store the posts. On different post types, for example code snippets, It would be nicer to be able to use snippet.code instead of snippet.content, or always having to remember what each attribute represents.
Time for a magic trick.
alias_attribute :code, :content
alias_attribute :title, :header
alias_attribute :url, :cite
This code does the exact same as above (getters, setters and nice names). Just in 3 lines, instead of 18.
alias_attribute(new_name, old_name)
That's a wrap. Thank you Paul Cortens for the kick in the right direction with alias_method.
