diff options
author | Rafael França <rafaelmfranca@gmail.com> | 2017-08-11 14:54:47 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-08-11 14:54:47 -0400 |
commit | 72e311c3dbf3bf7d7684176680ae0badf4c2c3cc (patch) | |
tree | 1ccd5df8ed0adf1e4dcf2bcea8d40d4f5c6cb05e /activestorage/lib | |
parent | 9774322246971737329b3d4c15d3a9796d658c2e (diff) | |
parent | bef99313e97d77cb94561411756d237ada4af27f (diff) | |
download | rails-72e311c3dbf3bf7d7684176680ae0badf4c2c3cc.tar.gz rails-72e311c3dbf3bf7d7684176680ae0badf4c2c3cc.tar.bz2 rails-72e311c3dbf3bf7d7684176680ae0badf4c2c3cc.zip |
Merge pull request #30201 from kamipo/eval_active_storage_attached_name_only_once
Evaluate `@active_storage_attached_#{name}` only once
Diffstat (limited to 'activestorage/lib')
-rw-r--r-- | activestorage/lib/active_storage/attached/macros.rb | 20 |
1 files changed, 8 insertions, 12 deletions
diff --git a/activestorage/lib/active_storage/attached/macros.rb b/activestorage/lib/active_storage/attached/macros.rb index 6bd0240606..eb877f10c0 100644 --- a/activestorage/lib/active_storage/attached/macros.rb +++ b/activestorage/lib/active_storage/attached/macros.rb @@ -22,13 +22,11 @@ module ActiveStorage # If the +:dependent+ option isn't set, the attachment will be purged # (i.e. destroyed) whenever the record is destroyed. def has_one_attached(name, dependent: :purge_later) - define_method(name) do - if instance_variable_defined?("@active_storage_attached_#{name}") - instance_variable_get("@active_storage_attached_#{name}") - else - instance_variable_set("@active_storage_attached_#{name}", ActiveStorage::Attached::One.new(name, self)) + class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name} + @active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self) end - end + CODE has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record has_one :"#{name}_blob", through: :"#{name}_attachment", class_name: "ActiveStorage::Blob", source: :blob @@ -63,13 +61,11 @@ module ActiveStorage # If the +:dependent+ option isn't set, all the attachments will be purged # (i.e. destroyed) whenever the record is destroyed. def has_many_attached(name, dependent: :purge_later) - define_method(name) do - if instance_variable_defined?("@active_storage_attached_#{name}") - instance_variable_get("@active_storage_attached_#{name}") - else - instance_variable_set("@active_storage_attached_#{name}", ActiveStorage::Attached::Many.new(name, self)) + class_eval <<-CODE, __FILE__, __LINE__ + 1 + def #{name} + @active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self) end - end + CODE has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment" has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "ActiveStorage::Blob", source: :blob |