如何根据配置添加 has_one_attached ?

问题描述 投票:0回答:1

我有一个 gem,如果使用 active_storage 启用配置,我想生成一个二维码

app/config/initializers/cryptocoin_payable.rb

CryptocoinPayable.configure do |config|
  config.qrcode = :active_storage
end
class CryptocoinPayable::CoinPayment < ActiveRecord::Base

if CryptoCoinPayable::Configuration.qrcode == :active_storage
 has_one_attached :qrcode
end

end

它不起作用,因为

CryptoCoinPayable::Configuration is nil

我尝试将其放在初始化之后

module CryptocoinPayable
end

if defined?(Rails)
  module CryptocoinPayable
    class Railtie < Rails::Railtie

      initializer 'cryptocoin_payable.active_storage' do
        ActiveSupport.on_load(:after_initialize) do
          require 'cryptocoin_payable/coin_payment'
          if (CryptocoinPayable.configuration == :qrcode)
            CryptocoinPayable::CoinPayment.has_one_attached(:qrcode)
           end
        end

      end

      rake_tasks do
        path = File.expand_path(__dir__)
        Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
      end
    end
  end
end

require 'cryptocoin_payable/config'
require 'cryptocoin_payable/errors'
require 'cryptocoin_payable/version'
require 'cryptocoin_payable/adapters'

但是它不起作用“qrcode”是未定义的方法

如何根据配置制作 `has_*one_*attached` ??

这是回复:https://github.com/sbounmy/cryptocoin_payable

ruby-on-rails ruby rubygems rails-activestorage
1个回答
0
投票

所以解决方案是:

确保我们正确初始化

after
active_storage 得到反映。 https://github.com/rails/rails/blob/9064735ec5cd3c679f8ffabc42532dd85223af58/activestorage/lib/active_storage/engine.rb#L171(如果在附加后尝试,将会引发不受支持的宏错误)

      initializer 'cryptocoin_payable.active_storage', after: 'active_storage.reflection' do
    require 'cryptocoin_payable/coin_payment'
    config.after_initialize do
      if CryptocoinPayable.configuration.qrcode?
        CryptocoinPayable::CoinPayment.has_one_attached(:qrcode)
      end
    end
  end

还要确保 rspec 确实拾取了 Railtie,在我的情况下,我必须在 cryptocoin_payable (已定义?(Rails))之前在我的spec_helper 中要求“rails”

© www.soinside.com 2019 - 2024. All rights reserved.