1

I am new to ruby on rails but I am not finding the meaning of this line of code. I saw in the documentation of rails that select will build an array of objects from the database for the scope, converting them into an array and iterating through them using Array#select. Anyway I can’t understand the result of this line of code and on what it consists.

model.legal_storages.select{|storage| storage.send(document_type)==true}.last
2
  • There are many differences between the Rails version 3, 4 and 5. Please use the specific tag. Commented Oct 21, 2019 at 21:16
  • This doesn't provide an answer, but the code used seems a bit strange .If model.legal_storages isn't already loaded I would go for a direct query instead. model.legal_storages.where(document_type => true).last If model.legal_storages is loaded I would use the square bracket notation to make sure only attributes can be invoked. model.legal_storages.select{|storage| storage[document_type] }.last Commented Oct 21, 2019 at 23:13

1 Answer 1

4
model.legal_storages.select { |storage| storage.send(document_type) == true }.last - From the result of the last operation, select only the last element.
             |         |                                  |
             |         |                                   --------------------- For each element in model.legal_stores invoke
             |         |                                                         the method that is held by the variable document_type
             |         |                                                         and check if it's equal to true.
             |         |
             |          --------- Over the result of the last method,
             |                    call select to filter those elements where
             |                    condition in the block evaluates to true.
             |
              ------------------- Invoke the method legal_stores in model.
Sign up to request clarification or add additional context in comments.

5 Comments

A true masterpiece of ASCII art.
@max, I'll start the bidding at $50,000.
Thank you for your respose but what does storage.send(document_type) do in this case? It stores the records in an array in case the condition is true?
@johnbowlee It invokes the method name, stored in the document_type variable on storage. foo.send("bar") is similar to foo.bar but negates private and protected access.
storage.send(document_type) is the same to do method_name = :succ; 1.send(method_name) # => 2. send receives a method name (document_type), and then that method is invoked in the receiver (storage) @johnbowlee.

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.