aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/attached
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2017-08-12 01:59:36 +0900
committerRyuta Kamizono <kamipo@gmail.com>2017-08-12 01:59:36 +0900
commitbef99313e97d77cb94561411756d237ada4af27f (patch)
treed20eb473f4984b5e6d6dd11ac268ff7582988a5f /activestorage/lib/active_storage/attached
parentde80aa641290a03c023d00d2ffca368026335fe4 (diff)
downloadrails-bef99313e97d77cb94561411756d237ada4af27f.tar.gz
rails-bef99313e97d77cb94561411756d237ada4af27f.tar.bz2
rails-bef99313e97d77cb94561411756d237ada4af27f.zip
Evaluate `@active_storage_attached_#{name}` only once
Currently `"@active_storage_attached_#{name}"` in `define_method` is evaluated every call. It is better to evaluate it only once.
Diffstat (limited to 'activestorage/lib/active_storage/attached')
-rw-r--r--activestorage/lib/active_storage/attached/macros.rb20
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