views:

148

answers:

2

I have a model, Show and a module Utilities

class Show < ActiveRecord::Base
  include Utilities

   ...
   def self.something
      fix_url("www.google.com")
   end
end

My Utilities file is in lib/utilities.rb

module Utilities
  def fix_url(u)
    !!( u !~ /\A(?:http:\/\/|https:\/\/)/i ) ? "http://#{u}" : u
  end
end

But Rails is throwing a NoMethodError for "fix_url" when I call it in my show class. Do I have to do something different when including a module in my model?

Thanks!

+1  A: 

It worked for me. Have you tried restarting your server/console session?

Edit: If you want to just call Utilities.fix_url you can do that - no include/extend necessary.

Andy Gaskell
i did...maybe it has something to do with me calling the function from a class method...updating the question to be more accurate
Tony
I think I know what you're trying to do now. I updated my answer.
Andy Gaskell
+2  A: 

try injecting that mixin via the extend instead of include. Basically, because you are calling the mixin method from a class method, but including a mixin only makes its instance methods available. You can use the extend style to get class methods.

Search around for Ruby include and extend to learn the differences. A common pattern is to do it like here:

http://www.dcmanges.com/blog/27

Where you use the included hook to mixin both instance and class level methods.

@Tony - this works for me

class User < ActiveRecord::Base
  extend Utilities
  def self.test
    go()
  end
end

module Utilities
 def go
  puts "hello"
 end
end

From console:

>> User.test
hello
=> nil

At no point do I have to explicitly call a method with self.

Cody Caughlan
i don't really think i want to do Show.fix_url which is what extending would accomplish. I want Utilities to be a singleton object or just set of functions I can call. The functions inside should not be mixed in my classes
Tony
See my update.. I dont see why 'extend' is not giving you precisely what you want.
Cody Caughlan