Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new lambda literal syntax for activerecord callbacks

I wonder if this is possible?

after_create -> { some_method_from_model }, if: :should_be_executed?

Syntax is ok, but the Proc will be called/executed or just created?

like image 732
Arnold Roa Avatar asked Feb 21 '14 13:02

Arnold Roa


People also ask

What are callbacks in Ruby?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

How do you define lambda in Ruby?

In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. proc_demo = Proc. new { return "Only I print!" }

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

If you want to call a method on the model the best approach would be passing the model as an argument for your lambda, and then using it to invoke the desired method, like so:

after_create -> (model) { model.some_method }, if: :execution_condition_satisfied?

This is because the value of self inside the lambda isn't the model but a Proc object and, without an explicit receiver, Ruby tries to invoke the method in self.

In your example, Ruby will try to find some_model_method in the Proc object. So no, your example would not work, but that's not related to the new lambda literal syntax.

I hope it helps ;)

like image 188
Guilherme Franco Avatar answered Nov 16 '22 00:11

Guilherme Franco