Forum: Ruby on Rails Monkey Patching and acts_as_indexed

5a6000cee9967dd9cd56acaf03a22332?d=identicon&s=25 Wolfgang H. (wolfgang_h)
on 2013-03-10 22:31
Hi,
I've monkey patched ActiveRecord::Base in a way so that every model
class knows which attributes are "important".

So in my model I can now do sth like this:

class User < ActiveRecord::Base
  attribute_order :username, :password, :name, :mailaddress, :usergroup,
:created_at
  acts_as_indexed :fields => self.sorted_attributes
end

The monkey-patch looks like this:

class ActiveRecord::Base

  def self.attribute_order(*values)
    @_sorted_attributes = []
    values.collect do |v|
      @_sorted_attributes.push(v)
    end
  end

  def self.sorted_attributes
    if defined? @_sorted_attributes
      @_sorted_attributes
    else
      self.attribute_names.map do |a|
        a.to_sym
      end
    end
  end
end

Now I'd like to add the acts_as_indexed method to ALL my models by
adding it into the monkey-patch:

class ActiveRecord::Base
  acts_as_indexed :fields => self.sorted_attributes
  ...
end

This doesn't work as the sorted attributes don't seem to exist when the
Class is Inheriting from ActiveRecord::Base, and the acts_as_indexed is
called too early. How could I delay the call of acts_as_indexed until
the class has been initialized? putting it into attribute_order doesn't
help, because this method must not be called by every model.

Wolfgang
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.