Today I Learned

A Hashrocket project

Write and Read Rails Attributes with Aliases

Lately I’ve been using a nice alias for writing record attributes in Rails, []=. Behold:

[1] pry(main)> d = Developer.new
=> #<Developer:0x007ff7130f8ef0
[2] pry(main)> d[:username] = 'isaacemard'
=> "isaacemard"
[3] pry(main)> d.username
=> "isaacemard"

That’s all it takes. There’s a getter variant, too:

[4] pry(main)> d[:username]
=> "isaacemard"

Here’s how I used it today:

# app/models/developer.rb
before_create :generate_slug

def generate_slug
   self[:slug] ||= SecureRandom.hex(5)
end

To me this code reads a lot more nicely than write_attribute(attr_name, value). These aliases have been a part of Rails since at least 2012.

Source

h/t Mike Chau and Chris Erin

Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.