I recently started a new internship at Buzzstarter working with a team of experienced developers. One of the benefits of this internship is to view how good code is written. My first two weeks involved viewing their application’s source code and using similar techniques to build an introduction project.
A specific instance of seeing good code was when I saw a class method called enum.
def self.enum(options)
options.each do |attr, values|
values_method = attr.to_s.pluralize
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{values_method}
#{values}
end
def #{attr}
self.class.#{values_method}[read_attribute(:#{attr})]
end
def #{attr}=(value)
idx = self.class.#{values_method}.index(value.to_sym)
raise 'Enum not found' unless idx
write_attribute(:#{attr}, idx)
end
RUBY
end
end
The method uses a bit of meta-programming, or at least that’s what I think this is doing, to write attributes to the database. The difference is that the values being written to the database are integer values instead of strings. As it was explained to me, this is a feature MySQL has, but PostgreSQL does not have. This allows for both reading and writing attributes to be quicker. You would then use the the enum
method like so.
enum current_status: [:off, :on]
The enum
method creates a getter and setter using the attribute current_status
with the value being the index of the value within the values array passed in.
There are too many instances already where I’ve read some code and was left smiling about the new technique I just learnt. Not only does viewing the application’s source code show me how good code is written, but making the introduction project has me writing better code.
I am fortunate that I have one of the engineers reviewing my code via code reviews. During these code reviews, Radil, would comment on the specific lines with what I needed to change. I would make the necessary changes until I can create a branch with the feature working, then I would create another pull request. There are about ten parts to the project, but I am still only on the third part. I can already tell there is much more for me to learn.