Skip to content

Instantly share code, notes, and snippets.

@micahboyd
Created April 29, 2019 23:24
Show Gist options
  • Select an option

  • Save micahboyd/3a0ea31cbd7d87d3e7cf23a952e0b70b to your computer and use it in GitHub Desktop.

Select an option

Save micahboyd/3a0ea31cbd7d87d3e7cf23a952e0b70b to your computer and use it in GitHub Desktop.
Create give defalt values to attrs
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