Ruby class inheritance or any other problem

my ruby ​​class (on rails) looks like this:

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 in some other way?

thank!

-2


source to share


2 answers


If some_action fits like a class method, I would 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 to be a convenience method, then I would do as Hates_ said.



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

      

The solution for me usually is whether some_action is a more useful method (e.g. generating a random key, in which case I would choose the first form), or if this is the entry point into something more complex (e.g. a parser, in this case I would have chosen the second form).

+2


source


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

      

+1


source







All Articles