rubyist
rubyist

Reputation: 3132

create objects in ruby with our own custom method in ruby

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.??

Upvotes: 1

Views: 54

Answers (4)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

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

Upvotes: 4

Dave Newton
Dave Newton

Reputation: 160191

class User
  def self.generate
    new
  end
end

Upvotes: 2

Lukas Baliak
Lukas Baliak

Reputation: 2869

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

class User
  def self.generate
    self.new
  end
end

obj = User.generate

Upvotes: 0

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Create a class method called generate inside your User class

Upvotes: 0

Related Questions