代码之家  ›  专栏  ›  技术社区  ›  Topher Fangio

Rails 3引擎-为用户提供配置

  •  7
  • Topher Fangio  · 技术社区  · 14 年前

    有没有人有任何链接到一个适当的或公认的方式来做这件事?

    编辑: 作为一个更新,我想出了一个体面的方法来做这件事。代码如下。

    # file: lib/my_engine.rb
    module MyEngine
    
      class Engine < Rails::Engine
    
        initializer "my_engine.configure_rails_initialization" do |app|
          # Engine configures Rails app here, this is not what my question was about
        end
    
      end
    
      # This is what I was trying to figure out
      def self.config(&block)
        @@config ||= MyEngine::Configuration.new
    
        yield @@config if block
    
        return @@config
      end
    
    end
    

    这允许任何使用我的引擎的应用程序在它们的任何初始值设定项或environment.rb文件中进行如下配置,调用 MyEngine::Configuration 班级:

    MyEngine.config do |config|
      config.some_configuration_option = "Whatever"
    end
    
    3 回复  |  直到 11 年前
        1
  •  6
  •   Keith Schacht    14 年前

    简短回答:

    module YourEngineClass
      class Engine < Rails::Engine
        config.param_name = 'value'    
      end
    end
    

    然后在main engine.rb中可以访问:

    config.param_name
    

    更长的答案:我创建了一个存根引擎,其中包括这个和许多其他您需要的标准配置,您可以将其用作起点:

    http://keithschacht.com/creating-a-rails-3-engine-plugin-gem/

        2
  •  5
  •   austen    11 年前

    我个人喜欢这个图案 Devise 在引擎的模块中定义类方法,然后在父应用程序中定义初始值设定项。

    module YourEngine
      class << self
        attr_accessor :your_config_var
      end
    
      def self.setup(&block)
        # You can yield your own object encapsulating your configuration logic/state
        yield self
      end
    end
    

    在父应用程序的初始值设定项中调用类方法

    YourEngine.setup do |config|
      config.your_config_var = "nyan cat"
    end
    

    现在您可以自由访问 your_config_var 在引擎的初始化过程中。您可以在引擎的 config/initializers 目录或使用 Rails Initializer

    我喜欢这种方法,因为您可以更好地控制向客户端公开的配置对象,并且不会重写引擎的 config 方法。

        3
  •  4
  •   nicolas    12 年前

    #lib/my_engine.rb
    require 'rails'
    
    module MyEngine
      class Engine < Rails::Engine
    
      end
    
      def self.config(&block)
        yield Engine.config if block
        Engine.config
      end
    end