Skip to content

Instantly share code, notes, and snippets.

@holysugar
Last active December 30, 2015 21:39
Show Gist options
  • Save holysugar/7888652 to your computer and use it in GitHub Desktop.
Save holysugar/7888652 to your computer and use it in GitHub Desktop.
module AttrAccessorWithDefault
extend ActiveSupport::Concern
module ClassMethods
def attr_accessor_with_default(key, &block)
define_method(key) do
instance_variable_get("@#{key}") || instance_eval(&block)
end
define_method("#{key}=") do |v|
instance_variable_set("@#{key}", v)
end
end
end
end
@holysugar
Copy link
Author

昔の Rails のみたいに値も入れられるようにするのがいいのかなあとも思うが、それこそ initialize でやれという気もする。というログ

@holysugar
Copy link
Author

instance_variable_get とか使わないとだめって指摘を受けた

@holysugar
Copy link
Author

でも元の Rails の実装 の方がそもそもよいのでもうやめよう

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment