Reputation: 3132
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
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
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
Reputation: 2390
Create a class method called generate
inside your User
class
Upvotes: 0