Freeze Your Constants in Ruby

Close-up photograph of a ruby gemstone
Photo by Joshua Fuller on Unsplash
class Txn
ACTIONABLE_STATES
= [:authenticated, :to_settle]
DONE_STATES = [:settled, :declined]
end
txn.state
# :settled
txn.state.in? ACTIONABLE_STATES
# true
def some_method
all_states
= Txn::ACTIONABLE_STATES.concat(Txn::DONE_STATES)

all_states.each do |state|
# ...
end
end
ACTIONABLE_STATES = [:authenticated, :to_settle].freeze
DONE_STATES = [:settled, :declined].freeze
class Txn
STATES =
{
actionable: [:authenticated, :to_settle],
done: [:settled, :declined]
}.freeze
end
class States
attr_accessor :done, :actionable
def initialize
@actionable = [:authenticated, :to_settle]
@done = [:settled, :declined]
end
end
class Txn
STATES =
States
.new.freeze
end
Txn::STATES.actionable.concat(Txn::STATES.done)
Txn::STATES.actionable
# [:authenticated, :to_settle, :settled, :declined]
Txn::STATES.actionable = [:foo, :bar]
# can't modify frozen Array (FrozenError)

Patrick is a software engineer from New England. Today, he resides in Seattle where he enjoys playing chess and ice hockey.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store