views:

163

answers:

2

my ruby (on rails) class looks like:

class Foo def self.method1 someAction end

def self.method2 someAction end

def someAction //doSmth end end

any ideas how to make this work or achieve the same behavior some other way?

thanks!

+1  A: 

You cannot call an instance method from a class method, without an actual instance of the class itself. You can do it as such:

class Foo 

    def self.method1 
         myFoo = Foo.new
         myFoo.someAction 
    end

    def someAction 
         //doSmth 
    end 

end
Hates_
thanks for the answer!however, as someAction is rather a helper, i didnt want to make a new instance for it...and then a cool idea struck me. i just defined it next to the clas :))ah, stupid me :/
Mantas
Not worth a down vote, but you shouldn't use the classes class name in a method. `myFoo = new` will work.
Chris Lloyd
+2  A: 

If some_action is appropriate as a class method, I'd do it like this:

 class Foo
   def self.method1
     some_action
   end
   def self.some_action
     # do stuff
   end
   def some_action
     self.class.some_action
   end
 end

If method1 is supposed to be a convenience method, then I'd do like Hates_ said to.

 class Foo
   def self.method1
     self.new.some_action
   end
   def some_action
     # do stuff
   end
 end

The decision for me is usually whether some_action is more of a utility method (like generating a random key, in which case I'd pick the first form), or if it's an entry point to something more complex (like a parser, in which case I'd pick the second form).

Matt Burke