【问题标题】:Change argument before passing to hook in rails generator在传递到rails生成器中的钩子之前更改参数
【发布时间】:2012-12-15 18:17:21
【问题描述】:

我正在尝试制作简单的视图生成器并使用 DRY 原则,我不想拥有自己的 html (erb/haml/slim) 模板。我希望我的生成器连接到现有的模板引擎并传递一些参数。

我的view_generator.rb 文件如下所示:

class ViewGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)
  argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"

def some_custom_method
  (...)
end

hook_for :template_engine, :as => :scaffold

end

一切都像这样正常工作。我想在我的some_custom_method 中添加几个属性:

def some_custom_method
  new_attribute = Rails::Generators::GeneratedAttribute.new("description")
  new_attribute.type = :integer
  attributes << new_attribute
end

发生的情况是我在attributes 数组中插入new_attribute,但是当hook_for 执行时,attribute 变量恢复为从命令行传递的原始变量。

我怎样才能绕过这个?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 thor


    【解决方案1】:

    在调用some_custom_method 时,属性已经设置(通过ARGV)并且通过检查代码我看不到从那里更改它们的明确方法。您可以通过在生成器中覆盖 start 类方法并直接操作 args 来使用另一种方法,如下所示:

    class ViewGenerator < Rails::Generators::NamedBase
      # your code ...
      def self.start(args, config)
        args.insert(1, 'description:integer') # 0 being the view name
        super
      end
    end
    

    【讨论】:

    • 感谢您的回答!我插入了那个方法,但它仍然不起作用。我尝试将其设为公开和私有。另外,我不确定它是否会被调用,因为我插入了一些调试“puts”调用,但没有打印到控制台。
    • 我的错,我使用了错误的函数名称,请重新检查答案。
    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 2019-05-15
    • 2011-08-09
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多