Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
 
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 Aug 31 '09 at 3:45
 
See my update.. I dont see why 'extend' is not giving you precisely what you want. –  Cody Caughlan Aug 31 '09 at 3:58

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.

share|improve this answer
 
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 Aug 31 '09 at 3:09
 
I think I know what you're trying to do now. I updated my answer. –  Andy Gaskell Aug 31 '09 at 4:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.