Ruby mixin最佳实践

时间:2013-11-14 14:19:48

标签: ruby-on-rails ruby

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

问题是我无法从Configurable模块访问@@ config,实际上当我在@object上调用entropy_config时。我做错了什么?

1 个答案:

答案 0 :(得分:0)

首先,你做错了。 Rails是在MVC架构上推动很多的框架。让模型了解表单标题是错误的。为此我会使用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了解详情