title: How to "dynamically" open a class so to add to it a scope method that makes use of a local variable?
body: <p>I am using Ruby on Rails v3.2.2. In a module I am trying to "dynamically" open a class so to add to it a Ruby on Rails "scope method" that makes use of a local variable, this way:</p>
  
  <pre><code>module MyModule
    extend ActiveSupport::Concern
  
    included do
      # Note: The `CLASS_NAME` is not the class where `MyModule` is included. That
      # is, for instance, if the including class of `MyModule` is `Article` then
      # the `CLASS_NAME` is `User`.
      CLASS_NAME           = self.get_class_name.constantize # =&gt; User
      counter_cache_column = self.get_counter_cache          # =&gt; "counter_count"
  
      class CLASS_NAME
        def self.order_by_counter
          order("#{counter_cache_column} DESC")
        end
      end
    end
  end
  </code></pre>
  
  <p>If I run the above code, I get the following error:</p>
  
  <pre><code>NameError
  undefined local variable or method `counter_cache_column' for #&lt;Class:0x0000010775c558&gt;
  </code></pre>
  
  <p>It happens because the <code>counter_cache_column</code> in not called in the context of the module. How should I properly state the <code>order_by_counter</code> scope method? </p>
  
  <hr>
  
  <p><em>Bonus</em>: What do you advice about the above "so dynamic" implementation?</p>