Should I make method calls during initialization when using Ruby?

I am creating a Calendar object. It is important that I have both a date object and a date as a string.

class Calendar def initialize(on, off, date_string) @on = on.to_i @off = off.to_i @date_string = date_string end end 

I have a method that converts a date to a date object. How to do this, I process this during initialization. Do I insert a dummy value and then call later? I call it from inside initialization. What is more idiomatic of Ruby?

+4
source share
4 answers

I would put this directly in the initializer as follows:

 class Calendar DATE_FORMAT = "%d/%m/%Y" def initialize(on, off, date_string) @on = on.to_i @off = off.to_i @date = Date.strptime(date_string, DATE_FORMAT) end end 
+1
source

A more object-oriented way is to transform as early as possible and save a rich object (here: Date) inside your new object. Perhaps you need to convert the given date_or_string to a date.

The implementation may be:

 class Calendar def initialize(on, off, date_or_string) @on = on.to_i @off = off.to_i @date = convert_to_date(date_or_string) end def convert_to_date(date_or_string) ... # Implementation here end end 
+2
source

You might want to write an assignment method:

 def date=(date_string) @date = ...(date_string) end 

It may be useful to convert others in the same way, if necessary, and then declare readers, if applicable:

 attr_reader :on, :off, :date 

In your constructor, you simply do this:

 def initialize(on, off, date_string) self.on = on self.off = off self.date = date_string end 
+1
source

I'm not sure if it makes sense to have too much logic in your initialize method - this means less flexibility in how you create your object. For example, I will have

 class Calendar def self.new_using_strings(on_string, off_string, date_string) on = on_string.to_i # Or Integer(on_string) off = off_string.to_i # Or Integer(off_string) date = convert_to_date(date_string) new(on, off, date) end def self.convert_to_date(date_string) # Implementation goes here end def initialize(on, off, date) @on, @off, @date = on, off, date end end 

Thus, if I want to create a calendar object using a date, not a date string, then I can do it.

I have not seen anyone else take this approach.

0
source

All Articles