Created
April 29, 2019 23:24
-
-
Save micahboyd/3a0ea31cbd7d87d3e7cf23a952e0b70b to your computer and use it in GitHub Desktop.
Create give defalt values to attrs
This file contains hidden or 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
| module AttrSet | |
| def attr_set(options = {}) | |
| options.each do |name, default_value| | |
| define_method("#{name}=") do |new_value| | |
| instance_variable_set("@#{name}", new_value) | |
| end | |
| define_method(name) do | |
| instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : | |
| instance_variable_set("@#{name}", default_value) | |
| end | |
| end | |
| end | |
| end | |
| class Sample | |
| extend AttrSet | |
| attr_set val: 'value1', val2: 'value2' | |
| end | |
| s = Sample.new | |
| s.val # => 'value1' | |
| s.val2 # => 'value2' | |
| s.val = 'new val' | |
| s.val # => 'new val' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment