Martin
Martin

Reputation: 11336

Calling a method from external matching class in Rails

I have many different classes under /lib/ folder with many actions.

Before saving an object I need to call a method from a class that matches its name with an attribute inside the object i.e. given this

User.gateway = "something"

I need to call myfunction from something class before the object is saved.

Not sure how to do this.

Upvotes: 0

Views: 50

Answers (2)

Viktor Trón
Viktor Trón

Reputation: 8884

your question is quite ambiguous,is this what you need?

# user.rb
before_save :myfunction

protected

def myfunction
   g = self.gateway
   case g 
   when String | Symbol 
     begin
       g.classify.constantize.myfunction
     rescue NameError
       # if there is no something class
     end
   else
     # no good value
   end
end

    enter code here

Upvotes: 1

lucapette
lucapette

Reputation: 20724

constantize and classify will do the job for you. Suppose you have:

class Foo
end

and the "foo" string. You can do:

"foo".classify.constantize.new.myfunction

Upvotes: 1

Related Questions