can anybody please elaborate what's happening in the code ?
Please post the code so that I may be able to assist you better.
Please note these forums are separate from the code area, so please transfer the code here manually.
def create_record(attributes, raise_error = false) record = build_record(attributes) yield(record) if block_given? saved = record.save set_new_record(record) raise RecordInvalid.new(record) if !saved && raise_error record end
Here's a line-by-line analysis of what's happening in your code:
def create_record(attributes, raise_error = false): You are creating a new method/function called
create_recordwhich takes in two arguments:
raise_errorhas a default value of
record = build_record(attributes): You are defining a variable
recordto be equal to the result returned by the method/function
build_recordwhich takes in an argument
yield(record) if block_given?: You are calling a method
yieldwhich takes an argument
record. Depending on the result of that which is
falseindicated by the
?in it, you are entering the conditional and testing a method
block_given?which takes no arguments.
saved = record.save: You are setting a variable called
savedto the value of
record.save, which, presumably, is a method of the
set_new_record(record): You are calling a method/function
set_new_recordwhich takes in an argument
record: You are returning the variable
end: You are notifying Ruby of the end of the method definition.
Was this sufficient, or do you need more? Please let me know.
I think this much will do !
thanks mate .
Thanks for the detailed explanation. But how about this line?:
- raise RecordInvalid.new(record) if !saved && raise_error
could you please explain it
Apologies, I hadn't seen that line previously.
That time means that
if !saved && raise_error is a
true expression, then to raise an error of type
RecordInvalid for the
raise_error are previously defined methods or functions that help determine whether or not the need to raise an error is valid.
thks for your quick reply!
However, way too advanced for me, many stuff there that I have not seen before... I guess I got to be patient and keep going.
Don't worry, with practice it will make sense.