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?
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.
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!" }
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With