I'm trying to initialize a singular class in my RoR application. This Batch class is not connected to any other class, it is used solely for the Rails API I have set up.
This is the Batch class:
class Batch < ActiveRecord::Base
before_create :access_bucket
def access_bucket
s3 = AWS::S3.new
bucket = s3.buckets['curateanalytics']
bucket.objects.each do |obj|
if obj =~ /swipe batches/i && obj =~ /jpg/i
self.sort_objs(obj.key)
end
end
end
def sort_objs(url)
swipe = url.split("swipe batches/").last
batch_id = url.split("swipe batches/")[1]
folder = swipe.split("/")[0]
self.initialize(batch_id, folder, url)
end
def initialize()
batch = Batch.new
batch.batch_id = batch_id
batch.folder = folder
batch.url = url
batch.save!
end
end
I honestly had no idea where to go so I created a before_create :create_batch
method in my User class:
class User < ActiveRecord::Base
has_one :like
has_one :outfit
has_one :wardrobe
before_create :create_batch
after_create :create_wardrobe, :create_outfit, :create_like
serialize :preferences
def self.from_omniauth(auth_hash)
where(auth_hash.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.curate_user_id = "curate"+rand(9).to_s+rand(9).to_s+rand(9).to_s+
rand(9).to_s+rand(9).to_s
user.provider = auth_hash.provider
user.uid = auth_hash.uid
user.name = auth_hash.info.name
user.email = auth_hash.info.email
user.image = auth_hash.info.image
user.oauth_token = auth_hash.credentials.token
user.oauth_expires_at = Time.at(auth_hash.credentials.expires_at)
user.preferences = { height: nil, weight: nil, age: nil, waist_size: nil, inseam: nil, preferred_pants_fit: nil, shirt_size: nil, preferred_shirt_fit: nil, shoe_size: nil}
user.save!
end
end
private
def create_batch
@batch = Batch.new
@batch.save!
end
end
When I ran the server I received the message that the stack was too deep. Am I wrong in thinking that this path should access the Batch class and the Batch.access_bucket method which would then lead to the initialize method?
Delete initialize method in the Batch class.
When you call new on a Class, it instantiates an object and call initialize on it. So when you call Batch.new in create_batch method of your User class, the initialize method of you Batch class is called. The problem is that Batch#initialize method calls Batch.new inside it, so another Batch#initialize is invoked, which calls Batch.new inside it, which again calls another Batch#initialize, and infinite cycle of Bathc.new and Batch#initialize follows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.