ruby-on-railsalias-methodalias-method-chain

alias_attribute and creating and method with the original attribute name causes a loop


Im trying to dynamically create a method chain in one attribute in my model. By now I have this function:

def create_filtered_attribute(attribute_name)
          alias_attribute "#{attribute_name}_without_filter", attribute_name

          define_method "#{attribute_name}" do
            filter_words(self.send("#{attribute_name}_without_filter"))
          end
end

so I receive a string with the attribute name, alias it for '_without_filter' (alias_method or alias_method_chain fails here, because the attribute isnt there when the class is created), and I create a new method with the attribute name, where I filter its contents.

But somehow, when I call "#{attribute_name}_without_filter" it calls my new method (i think because the alias_attribute some how), and the program goes into a stack loop.

Im trying to rename that attribute, so I can use its name for a method...

Can someone please enlighten me on this.


Solution

  • There is a difference between alias_method and alias_attribute. alias_method actually makes a copy of the old method, whereas alias_attribute just defines new methods, which call old ones.

    Note, that model.attribute and model.attribute= methods in ActiveRecord simply call read_attribute and write_attribute, so you always can access your attribute, even if you override it's getter or setter:

      define_method "#{attribute_name}" do
        filter_words(self.read_attribute(attribute_name))
      end