2013-11-14 47 views
0

新红宝石\ 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时。我做错了什么?

+0

你是什么意思都进不去呢,该变量不存在? –

回答

0

首先你做错了。 Rails是在MVC架构上推动了很多的框架。让你的模型知道表单标题是错误的。为此,我会使用导轨i18n宝石。对于参数的缘故这里的一些未经测试的代码,可能会回答你的问题:

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更多信息

+0

谢谢!这笔交易不仅仅是关于标题,更多的是关于管理配置,例如表单域设置或列表中的字段 – Eugene

+0

我仍然相信模型不适合它。如果您不想在视图中定义字段,则应为其创建一些单独的对象。看看activeadmin如何工作https://github.com/gregbell/active_admin – bcd

+0

btw ...作为Rails提示:无论何时你需要一些组件搜索rubygems.org(或ruby-toolbox.com),因为这是一个很好的机会有人已经开发出这个组件:) – bcd