Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active May 30, 2018 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/524caa7b0774ee830359e75e27707442 to your computer and use it in GitHub Desktop.
Save JoshCheek/524caa7b0774ee830359e75e27707442 to your computer and use it in GitHub Desktop.
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