5

I want to return custom collection on one of my model scope.. But I don't know why it shows error when I use do end block inside my lambda scope.. I am using rails 4.1.0 and ruby 2.1.2..

Here is my scope code inside my model:

scope :date, -> (from_date, to_date) do
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each do |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  end
  matches
end

It will show an error on this line: buff_matches.each do |match| with error message : SyntaxError: match.rb:15: syntax error, unexpected keyword_do_block, expecting keyword_end.

But if I change my code to be like this :

scope :date, -> (from_date, to_date) do
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each { |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  }
  matches
end

It will works fine. I want to use do end syntax since it will look cleaner than using curly brace. Do you have any idea why this error happened?

mario
  • 53
  • 1
  • 4
  • You can't use do/end unless you enclose the scope arguments in parenthesis. This is documented in more detail here https://github.com/bbatsov/ruby-style-guide/issues/270 – infused Sep 01 '14 at 06:11

1 Answers1

1

It seems like you've hit an edge case. I can't really explain why it fails but this fixes it and uses do..end blocks

scope :date, lambda do |from_date, to_date|
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each do |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  end
  matches
end
Joeyjoejoejr
  • 904
  • 5
  • 11
  • Unfortunately I'll have another error when I use this code. The error message is: *ArgumentError: tried to create Proc object without a block.* I can surpress the error by wrap the lambda inside braces like the solution here: http://stackoverflow.com/questions/16016668/scope-but-error-message-argumenterror-tried-to-create-proc-object-without-a-blo – mario Aug 31 '14 at 16:38