create objects in ruby with our own custom method in ruby

64 views Asked by At

I need to create an object with my own custom method in ruby instead of default new().

obj = User.new

If I need to create an object for a user with generate(), how this can be achieved. So when I type

obj = User.generate

it should create an object of User.

One way I understand is by aliasing the method with alias keyword.

Though I am not sure.

Is there any suggestion for doing it.??

4

There are 4 answers

0
Dave Newton On
class User
  def self.generate
    new
  end
end
3
Piotr Kruczek On

Create a class method called generate inside your User class

0
Lukas Baliak On

You can call your specific method and inside it call self.new

class User
  def self.generate
    self.new
  end
end

obj = User.generate
0
Jörg W Mittag On

As you say, you can just alias_method it:

 class << User
   alias_method :generate, :new
 end

You could also delegate:

class User
  def self.generate(*args, &blk)
    new(*args, &blk)
  end
end

Or, you could re-implement what Class#new does:

class User
  def self.generate(*args, &blk)
    obj = allocate
    obj.send(:initialize, *args, &blk)
    obj
  end
end