varblock_with(fruit: 'apple',vegetable: ->{'bean'})do |v|
putsv.class# => VarBlock::VarHashputsv.is_a?Hash# => true# from above, notice that a VarHash extends a Hash# therefore you can also use any Hash method as well like below.# NOT RECOMMENDED. use `varblock_get(v, :fruit)` instead when getting the value as it automatically evaluates the value, amongst others thingsputsv[:fruit]# => 'apple'putsvarblock_get(v,:fruit)# => 'apple'putsv[:vegetable]# => #<Proc:0x00...>putsvarblock_get(v,:vegetable)# => 'bean'# NOT RECOMMENDED. use `v.varblock_with(fruit: 'banana')` block instead when overwriting the value, as encapsulation is the main purpose of this gemv[:fruit]='banana'v.varblock_with(fruit: 'banana')do# ...endend
Options
:truthy?
mimics "AND" logical operator for merged variables
condition1=truecondition2=truecondition3=falsecondition4=truevarblock_withconditions: ->{condition1}do |v|
v.varblock_merged_withconditions: ->{condition2}do |v|
putsvarblock_get(v,:conditions,:truthy?)# => trueendv.varblock_merged_withconditions: ->{condition3}do |v|
putsvarblock_get(v,:conditions,:truthy?)# => falsev.varblock_merged_withconditions: ->{condition4}do |v|
# returns false because condition3 above is already false. This will not propagate and therefore would not run the proc above for condition4putsvarblock_get(v,:conditions,:truthy?)# => falseendendend
condition1=falsecondition2=falsecondition3=truecondition4=falsevarblock_withconditions: ->{condition1}do |v|
v.varblock_merged_withconditions: ->{condition2}do |v|
putsvarblock_get(v,:conditions,:any?)# => falseendv.varblock_merged_withconditions: ->{condition3}do |v|
putsvarblock_get(v,:conditions,:any?)# => truev.varblock_merged_withconditions: ->{condition4}do |v|
# returns true because condition3 above is already true. This will not propagate and therefore would not run the proc above for condition4putsvarblock_get(v,:conditions,:any?)# => trueendendend
I needed to find a way to group model validations in a Rails project because the model has lots of validations and complex if -> { ... } conditional logic. Therefore, in hopes to make it readable through indents and explicit declaration of "conditions" at the start of each block, I've written this small gem, and the code then has been a lot more readable and organised though at the expense of getting familiar with it.
TODOs
pass in also the binding of the current context where varblock_get is called into the variable-procs so that the procs are executed with the same binding (local variables exactly the same) as the caller context. Found dynamic_binding, but I couldn't think of a way to skip passing in binding as an argument to varblock_get in hopes to make varblock_get as short as possible
Contributing
pull requests and forks are very much welcomed! :) Let me know if you find any bug! Thanks