簡體   English   中英

動態包含Rails關注

[英]Dynamically including a Rails Concern

我的目標是根據設置的屬性將一組方法動態加載到ActiveRecord模型實例:

class Book < ActiveRecord::Base
  after_initialize do |cp|
    self.class.include "#{cp.subject}".constantize
  end
end

然后,我有以下擔憂:

module Ruby
    extend ActiveSupport::Concern
    def get_framework
        'rails'
    end
end

module Python
    extend ActiveSupport::Concern
    def get_framework
        'django'
    end
end

然后,當我分別運行它們時,我得到正確的框架字符串:

python_book = Book.create(:subject => 'python', :id => 1)
python_book.get_framework -> 'django'

ruby_book = Book.create(:subject => 'ruby', :id => 2)
ruby_book.get_framework -> 'rails'

我的問題是,當我在查詢中返回了兩本書時,關注點是結果集中的最后一個,並且沒有選擇正確的關注點方法。

Books.all.order(:id => 'asc').collect do |book|
    puts book.get_framework
end

# Result
['rails', 'rails']

我假設這是因為'include'發生在類級別而不是實例級別。 希望獲得有關如何清理和使之工作的幫助。

使用.extend可以將實例方法添加到Book的實例中。

擴展作用:

module Greeter
  def say_hello
    "Hello"
  end
end

irb(main):008:0> a = Object.new
=> #<Object:0x00000101e01c38>
irb(main):009:0> a.extend(Greeter)
=> #<Object:0x00000101e01c38>
irb(main):010:0> a.say_hello
=> "Hello"
irb(main):011:0> Object.new.say_hello
NoMethodError: undefined method `say_hello' for #<Object:0x00000101e196d0>

class Book < ActiveRecord::Base
  after_initialize do |cp|
    self.extend subject.constantize
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM