Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
One-time use setters
class Module
def attr_accessor(name, once: false)
ivar = "@#{name}"
define_method "#{name}=" do |value|
once && instance_variable_defined?(ivar) &&
raise(ArgumentError, "Already initialized #{name}!")
instance_variable_set ivar, value
end
attr_reader name
end
end
class Whatever
attr_accessor :resettable
attr_accessor :set_only_once, once: true
end
w = Whatever.new
w.resettable = 1
w.resettable # => 1
w.resettable = 2
w.resettable # => 2
w.set_only_once = 1
w.set_only_once # => 1
w.set_only_once = 2 # ~> ArgumentError: Already initialized set_only_once!
w.set_only_once
# ~> ArgumentError
# ~> Already initialized set_only_once!
# ~>
# ~> program.rb:6:in `block in attr_accessor'
# ~> program.rb:27:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.