Last active
May 30, 2018 01:53
-
-
Save JoshCheek/524caa7b0774ee830359e75e27707442 to your computer and use it in GitHub Desktop.
One-time use setters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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