0

Ruby\Rails は初めてで、恥を知れ :(

私は個人用のエンジンを開発しています (シンプルな管理パネル)。私が欲しいのは、次のようにメインアプリのモデルを構成できるようにすることです:

class User < ActiveRecord::Base

  include Entropy::Configurable

  entropy_config do
    form_caption 'Editing user'
  end
end

そして、エンジンのテンプレートでこれを行います:

<h1><%= @object.entropy_config :form_caption %></h1>

エンジンのモジュール:

module Entropy
  module Configurable

    def self.included(base)
      ## to call entropy_config in model class
      base.send :extend, ClassMethods
    end

    def entropy_config(arg)
      ## ... I'm missing this part
    end

    module ClassMethods

      @@config = { ... }

      def entropy_config (&block)
        class_eval &block
      end

      def form_caption(arg)
        // skipping class identification
        @@config[:user][:form_caption] = arg
      end
    end
  end
end

問題は、@object で entropy_config を呼び出すと、Configurable モジュールから @@config にアクセスできないことです。私が間違っていることは何ですか?

4

1 に答える 1

0

まず、あなたのやり方が間違っています。Rails は、MVC アーキテクチャに大きく貢献したフレームワークの 1 つです。モデルにフォームのキャプションを認識させるのは間違っています。そのためには、Rails i18n gem を使用します。議論のために、おそらくあなたの質問に答えるテストされていないコードをいくつか示します。

module Entropy
  module Configurable

    def self.included(base)
      ## to call entropy_config in model class
      base.send :extend, ClassMethods
    end

    def entropy_config(key)
      self.class.config[:user][key]
    end

    module ClassMethods

      cattr_accessor :config

      def entropy_config (&block)
        self.config ||= {}
        class_eval &block
      end

      def form_caption(arg)
        // skipping class identification
        self.config[:user][:form_caption] = arg
      end
    end
  end
end

詳細については、 http://apidock.com/rails/Class/cattr_accessorを参照してください。

于 2013-11-14T14:44:09.363 に答える