1

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

1
  • Why do you need this? I’m assuming there’s some specific reason why new doesn’t do what you want, otherwise just use new. Commented Jun 9, 2015 at 15:32

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2
class User
  def self.generate
    new
  end
end

Comments

0

Create a class method called generate inside your User class

3 Comments

Would this do: class User; def self.generate; puts "How now, brown cow?"; end; end?
Yes, just as others have posted below. But please, don't write it in one line
@CarySwoveland Not sure but I am hoping the first comment was a satirical jab at the answer unless I missed it in the docs I don't think new ever puts out How now, brown cow? :). @PiotrKruczek this isn't really and answer since the OP wanted to know how to create a generate method that acts like new which your answer does not cover.
0

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

class User
  def self.generate
    self.new
  end
end

obj = User.generate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.