简体   繁体   English

如何让rails引擎与主App交互

[英]How to get a rails engine to interact with main App

I am creating a rails engine used as an interface to a payment service. 我正在创建一个用作支付服务接口的rails引擎。 I have to handle the use cases where the payment service is sending me message outside of any transaction. 我必须处理支付服务在任何交易之外向我发送消息的用例。 I will take the following use case : 我将采用以下用例:

The engine receive a message that subscription FooBar42 has been correctly billed(through it's own routes). 引擎收到一条消息,说明订阅FooBar42已正确计费(通过它自己的路由)。 What does my engine do next? 我的引擎下一步做什么? If i start to call models specific to my app, my engine is only good for this app. 如果我开始调用特定于我的应用程序的模型,我的引擎只适用于此应用程序。 Only example i could find is Devise, but in devise, it just add methods to your user model and the engine handle how the user is stored and all the code. 只有我能找到的例子是Devise,但在设计中,它只是为您的用户模型添加方法,引擎处理用户的存储方式和所有代码。

How do i create a reusable system where my engine can call/trigger code in the main app ? 如何创建可重用的系统,我的引擎可以在主应用程序中调用/触发代码?

Do i override engine controller ? 我是否覆盖发动机控制器? Do i generate a service object with empty methods that will be used as an engine-app communication system? 我是否使用空方法生成服务对象,将其用作引擎应用程序通信系统?

You need to have a way to configure your engine either in an initializer or through calling class methods in your model, much like how you configure Devise to use your User model when you call devise in the body of the User class: 您需要有一种方法可以在初始化程序中或通过调用模型中的类方法来配置引擎,就像在User类的主体中调用devise时配置Devise以使用User模型一样:

class User < ActiveRecord::Base
  devise :database_authenticatable
end

For one of my engines I use an initializer that stores the classes the engine interacts with using a config object. 对于我的一个引擎,我使用初始化程序,它使用配置对象存储引擎与之交互的类。

Given a config object: 给定一个配置对象:

class Configuration
  attr_reader :models_to_interact_with

  def initialize
    @models_to_interact_with = []
  end
end

You can then provide a config hook as a module method in your main engine file in lib: 然后,您可以在lib的主引擎文件中提供配置挂钩作为模块方法:

require 'my_engine/configuration'

module MyEngine
  mattr_reader :config

  def self.configure(&block)
    self.config ||= Configuration.new
    block.call self.config
  end
end

Now when you're in the main app, you can create an initializer in config/initializers/my_engine.rb and add the models to your Configuration: 现在,当您在主应用程序中时,可以在config/initializers/my_engine.rb创建初始化程序,并将模型添加到您的配置中:

MyEngine.configure do |config|
  config.models_to_interact_with << User
  config.models_to_interact_with << SomeOtherModel
end

Now you have access to this from you engine without having to hardcode the model in your engine: 现在您可以从引擎访问此引擎,而无需在引擎中对模型进行硬编码:

# in some controller in your engine:

def payment_webhook
  MyEngine.config.models_to_interact_with.each do |model|
    model.send_notification_or_something!
  end
end

Hope that answers your question. 希望这能回答你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM