Report abuse

console


			
>> Quantity.get_or_create("1/2")
NoMethodError: undefined method `get_or_create' for Quantity:Class

>> IngredientPart.get_or_create("won't work but notice the failure is not on get_or_create")
NoMethodError: undefined method `find_by_name' for IngredientPart:Module

app/models/quantity.rb


			
class Quantity < ActiveRecord::Base
  include IngredientPart
  has_many :ingredients
end

lib/ingredient_part.rb


			
module IngredientPart
  def self.included receiver
    receiver.extend ClassMethods
  end

  module ClassMethods
    def get_or_create(str)
      str.strip!
      return nil unless str.length > 0

      if ! it = self.find_by_name(str)
        it = self.create( :name => str)
      end
      it
    end
  end
end