Dimitar Vouldjeff
Dimitar Vouldjeff

Reputation: 2117

Metaprogramming ActiveRecord Rails

I have the following code in my project`s lib directory

module Pasta  
  module ClassMethods
    def self.has_coordinates
      self.send :include, InstanceMethods     
    end
  end

  module InstanceMethods
    def coordinates
      [longitude ||= 43.0, latitude ||= 25.0]
    end
  end   

  ActiveRecord::Base.extend ClassMethods
end

And it should create a class method for ActiveRecord::Base - has_coordinates - which I can "assign" to models... But I receive the error undefined local variable or method 'has_coordinates'

Thanks in advance!

Upvotes: 0

Views: 717

Answers (2)

John Topley
John Topley

Reputation: 115412

Try this:

module Pasta
  def has_coordinates
    send :include, InstanceMethods
  end

  module InstanceMethods
    def coordinates 
      [longitude ||= 43.0, latitude ||= 25.0] 
    end     
  end
end

ActiveRecord::Base.extend Pasta

Upvotes: 0

elektronaut
elektronaut

Reputation: 2557

Dropping the self. in ClassMethods should do the trick.

module Pasta  
  module ClassMethods
    def has_coordinates
      self.send :include, InstanceMethods
    end
  end

  module InstanceMethods
    def coordinates
      [longitude ||= 43.0, latitude ||= 25.0]
    end
  end   

  ActiveRecord::Base.extend ClassMethods
end

Upvotes: 1

Related Questions