【问题标题】:Move model method from Rails app to a gem将模型方法从 Rails 应用程序移动到 gem
【发布时间】:2016-09-23 13:33:04
【问题描述】:

我正在 Rails 5 上创建一个 gem。

假设我有 SomeModelhello 方法,我在 myengine 中使用:

# app/models/myengine/someModel.rb
module Myengine
  class SomeModel < ApplicationRecord
    def self.hello
      puts 'hello world'
    end
  end
end

我想从默认应用程序中删除 hello 方法并将其存储到 gem 中,这样我可以仅在需要时将其插入。

我不知道要写什么来扩展模型,也不知道在哪里放置该文件。

我试图通过Rails guidelines,但它们太复杂了!几次尝试后我迷路了。 我不需要单表继承,我需要扩展那个特定的模型。

已经尝试过this answer,这似乎不太正确,而this one,不幸的是并没有说太多。

有什么想法吗?

【问题讨论】:

  • 也许您应该只使用 hello 方法编写模块并在应用程序中扩展模型而不是 gem 本身?
  • “使用hello 编写模块”和“在应用程序中扩展模型而不是gem 本身”是什么意思?我需要一个 gem,因为这是我正在做的更广泛的事情的一部分,必须在多个 Rails 应用程序上轻松复制。
  • 嘿@Aleksey,我想我成功了。

标签: ruby rubygems ruby-on-rails-5


【解决方案1】:

好吧,在挖了网,把我的头撞到墙上后,我终于得出了结论。

假设你想在你的默认应用引擎myengine中扩展SomeModel的功能:

# app/models/myengine/some_model.rb
module Myengine
  class SomeModel < ApplicationRecord
    # some code
  end
end

您可以在config/intializers 文件夹或lib/myplugin 文件夹中执行此操作。我展示了两者,第一个以关注方式,第二个使用自我方式


关注方式

在您的 gem 中,您可以使用 Concern 扩展 SomeModel 添加 hello 方法:

# myplugin/config/initializers/some_model_extension.rb
module Myplugin::SomeModelExtension

  extend ActiveSupport::Concern

  class_methods do
    def hello
        return "Hello world!"
    end
  end

end

class Myengine::SomeModel < ActiveRecord::Base
    include Myplugin::SomeModelExtension
end

您可以更新ClassMethods,但InstanceMethods 也是如此(如果您不知道实例方法和类方法之间的区别,您应该read this)。

如果您想添加has_manybelongs_to 之类的关联,您可以使用included do 作为this guy did


自我方式

这个也可以

# myplugin/lib/myplugin/some_model_extension.rb
module SomeModelExtension

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def hello
      return 'Hello world'
    end
  end

end

class Myengine::SomeModel < ActiveRecord::Base
    include SomeModelExtension
end
# myplugin/lib/myplugin.rb
require 'myplugin/some_model_extension'

如果您想了解更多,请查看Rails Guidelines

同样值得检查awesome answer


【讨论】:

  • 看来你做得很好!但是你为什么不使用ActiveSupport::Concern
  • 是的,我也这样做了。我仍在改进答案,因为它还不完全正确。但几乎就在那里。我的关联有问题……这不起作用。
  • 好的,关注方式没问题。第二种方法还可以,但不明白如何使关联起作用。就我可以使用 concern 而言,这并不重要;-)
  • 你应该使用它! =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2013-11-20
  • 2019-07-15
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多