Andy Donovan
Andy Donovan

Reputation:

Ruby on Rails - Share one method with 2 models

I have the following module

module SharedMethods

    # Class method
    module ClassMethods

        #
        # Remove white space from end of strings
        def remove_whitespace
            self.attributes.each do |key,value|
                if value.kind_of?(String) && !value.blank?
                    write_attribute key, value.strip
                end
            end
        end


    end

    #
    #
    def self.included(base)
        base.extend(ClassMethods)
    end

end

and I am using it in my models like

include SharedMethods
before_validation :remove_whitespace

However whenever I submit the form I get a "undefined method `remove_whitespace'" message

What can I do to correct this error?

Upvotes: 1

Views: 1403

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176352

That's because :remove_whitespace must be an instance method, not a class method.

module SharedMethods

  def self.included(base)
    base.send :include, InstanceMethods
  end

  module InstanceMethods

    # Remove white space from end of strings
    def remove_whitespace
      self.attributes.each do |key,value|
        if value.kind_of(String) && !value.blank?
          write_attribute key, value.strip
        end
      end
    end

  end

end

Unless you need the module to provide both class and instance methods, you can also skip the usage of self.included and simplify your module in this way:

module SharedMethods

  # Remove white space from end of strings
  def remove_whitespace
    self.attributes.each do |key,value|
      if value.kind_of(String) && !value.blank?
        write_attribute key, value.strip
      end
    end
  end

end

Upvotes: 2

Related Questions