Engineering

Our engineering is underpinned by principles that celebrate both the integrity of code and the ambition to innovate. This manifesto champions excellence, advocates for the adoption of cutting-edge technologies, and fosters an environment of continuous intellectual growth.

Avoid enums

Avoid using enums in ActiveRecord. While they seem like a great idea at first, they can cause problems down the road.

class Document < ActiveRecord::Base # ✗ Avoid this! enum status: [:active, :archived] end

Leaky abstraction

Enums are a way to use numbers instead of strings (eg, 1 instead of 'active'), but this abstraction can get leaky. In the example above, you can easily use :active and :archived as you would use any other value. Rails abstracts away the conversion of them into integers.

Document.where(status: :archived) # This actually does `Document.where(status: 1)`

However, there are cases where this doesn't apply. For instance:

# ✗ Throws an error Document.where("status = ?", "archived") # ✗ Throws an error Comment.joins(:document).where({ document: { status: :archived }}) # It should instead be written like this: archived = Document.statuses[:archived] Comment.joins(:document).where({ document: { status: archived }})

Insertion can get tricky

If you must use Enums, always assign explicit values to them. Consider the example above: if we were to add another status, we may be tempted to do it like so:

end This, however, will break all existing Document records. The new :pending status will be assigned a value of 0, which was the previous value of :active. With this, all previously active documents will now be :pending, and all previously archived documents will be :active.

class Document < ActiveRecord::Base - enum status: [:active, :archived] + enum status: [:pending, :active, :archived] end

Resources

Here are some more arguments against Enums: • Ruby on Enums and Rails 4.1 (hackhands.com) • Rails Enum is a Shap Knife (bendyworks.com) • Enums are a leaky abstraction, @rstacruz (github.com) • The many issues with Rails Enum (medium.com) Other resources: • Leaky abstraction (en.wikipedia.org)

Next: Design Playbook

Connect.

Mashup Garage, a premier software development team, specialises in crafting exceptional products for startups and enterprises. With expertise in React, Elixir/Phoenix, and Ruby on Rails, we deliver solutions that meet your unique needs. Our mission is to bring value backed by decades of technical expertise and global co-founding experience.

What do you need help with?

Build a project

Build a team

Consult

Speak to someone

Expect a guaranteed response from us in 1-2 business days.

United Kingdom

London

Islington, London

+44 738 777 3405

LDN

Philippines

Manila

3F Topy IV Building, 3 Economia Road, Bagumbayan, Quezon City, 1110

+63 917 3084089

MNL