Reputation: 802
I'm initializing a new object and setting the attributes (because there are no attributes for this particular object) before rendering a form like so:
def new
Book.new title: nil, author: nil, genre: nil, language: nil, ect...
end
This to me looks like a code smell.
I'm trying to set the attributes in a method within the model so I can increase readability by using: Book.new.set_attributes
. So my set_attributes
method in the Book model would look like:
def set_attributes
{posted: nil, company: nil, poster: nil, city: nil, state: nil, title: nil, body: nil, keywords: nil}
end
However this does not work (with or without the {}
brackets). Is it possible to call a method after using .new
?
Upvotes: 0
Views: 1485
Reputation: 2051
Ruby's constructor method is initialize
, not new
. You shouldn't try to define a method called new
. Do something like:
class Book
attr_accessor :title, :author
def initialize(title = nil, author = nil)
@title = title
@author = author
end
end
Upvotes: 2
Reputation: 20263
You don't need to initialize nil values. When calling Book.new, any values that are not provided in a hash (e.g., Book.new(title: 'Bozo', author: 'Clown')) will be nil automatically.
Upvotes: 0