Home > Net >  Rails 5 Why I always get default date in initialize method
Rails 5 Why I always get default date in initialize method

Time:10-14

I have class that get articles and two dates. My initialize method in class looks like that:

def initialize(articles:, date1: nil, date2: nil)
    @articles = articles
    @date1 ||= DEFAULT_DATE1
    @date2 ||= DEFAULT_DATE2
end

I don't know why my @date1 and @date2 has DEFAULT_DATE value even if I send parameters like that:

Example.new(articles: articles, date1: '2021-10-10', date2: '2021-10-11')

Where is the problem?

CodePudding user response:

You should be checking for the params you receive and then assign accordingly.

Changing the code to this will work

def initialize(articles:, date1: nil, date2: nil)
  @articles = articles
  @date1 = date1 || DEFAULT_DATE1
  @date2 = date2 || DEFAULT_DATE2
end

The Issue and explanation:

When you do this

@date1 ||= DEFAULT_DATE1

It's checking if @date1 has any value (which it does not) so you get DEFAULT_DATE1 assigned to the @date1

CodePudding user response:

Where is the problem?

You never use the arguments date1 and date2. You probably want to assign them to their respective instance variables.

Unless you have very specific needs, it's easier to move the defaults right into the argument definition:

def initialize(articles:, date1: DEFAULT_DATE1, date2: DEFAULT_DATE2)
  @articles = articles
  @date1 = date1
  @date2 = date2
end
  • Related