title: Dynamically including a Rails Concern
body: <p>My objective is to dynamically load a set of methods to an ActiveRecord model instance based on an attribute that's set:</p>
  
  <pre><code>class Book &lt; ActiveRecord::Base
    after_initialize do |cp|
      self.class.include "#{cp.subject}".constantize
    end
  end
  </code></pre>
  
  <p>I then have the following concerns:</p>
  
  <pre><code>module Ruby
      extend ActiveSupport::Concern
      def get_framework
          'rails'
      end
  end
  
  module Python
      extend ActiveSupport::Concern
      def get_framework
          'django'
      end
  end
  </code></pre>
  
  <p>Then, when I run these separately, I get the correct framework string:</p>
  
  <pre><code>python_book = Book.create(:subject =&gt; 'python', :id =&gt; 1)
  python_book.get_framework -&gt; 'django'
  
  ruby_book = Book.create(:subject =&gt; 'ruby', :id =&gt; 2)
  ruby_book.get_framework -&gt; 'rails'
  </code></pre>
  
  <p>My problem is that when I have both of the books returned in a query, the Concern is included is the last in the result set and is not picking up the correct Concern methods. </p>
  
  <pre><code>Books.all.order(:id =&gt; 'asc').collect do |book|
      puts book.get_framework
  end
  
  # Result
  ['rails', 'rails']
  </code></pre>
  
  <p>I am assuming that this is because the 'include' is happening at the class level and not the instance level. Would love some help as to how to clean this up and make this work. </p>