Techioz Blog

構成に応じて has_one_attached を追加するにはどうすればよいですか?

概要

構成がactive_storageで有効になっている場合にqrコードを生成したいgemがあります

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」は未定義のメソッドです

設定に応じてどうやって作ることができますか?

レスポは次のとおりです: https://github.com/sbounmy/cryptocoin_payable

解決策

したがって、解決策は次のとおりです。

active_storage が反映された後、正しく初期化されていることを確認してください。 https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://github.com/rails/rails/blob/9064735ec5cd3c679f8ffabc42532dd85223af58/activestorage/lib/active_storage/engine.rb#L171 (if you try after attached it will raise an unsupported Macro error)

      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

また、私の場合、cryptocoin_payable (定義済み?(Rails)) の前に spec_helper で ‘rails’ を要求する必要があったので、rspec がレールタイを選択することを確認してください。