正在初始化未连接到其他 class 的 class -- Rails 上的 Ruby

Initializing a class not connected to other classes -- Ruby on Rails

我正在尝试在我的 RoR 应用程序中初始化一个单一的 class。此批次 class 未连接到任何其他 class,它仅用于我设置的 Rails API。

这是批次 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

老实说,我不知道该去哪里,所以我在我的用户 class:

中创建了一个 before_create :create_batch 方法
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

当我 运行 服务器收到堆栈太深的消息时。我认为这条路径应该访问 Batch class 和 Batch.access_bucket 方法然后会导致初始化方法,我错了吗?

删除批处理中的初始化方法class。

当您在 Class 上调用 new 时,它会实例化一个对象并对其调用初始化。因此,当您在 User class 的 create_batch 方法中调用 Batch.new 时,将调用 Batch class 的初始化方法。问题是Batch#initialize方法在里面调用了Batch.new,所以调用了另一个Batch#initialize,在里面调用了Batch.new,又调用了另一个Batch#initialize,无限循环Bathc.new 和 Batch#initialize 如下。