Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camping's path building method

Could someone explain for me this part of the code from Lucky Stiff's Camping micro-framework:

# Simply builds a complete path from a path +p+ within the app.  If your
# application is mounted at <tt>/blog</tt>:
#
#   self / "/view/1"    #=> "/blog/view/1"
#   self / "styles.css" #=> "styles.css"
#   self / R(Edit, 1)   #=> "/blog/edit/1"
#
def /(p); p[0] == ?/ ? @root + p : p end

Source

like image 905
Thanh DK Avatar asked Jan 23 '26 10:01

Thanh DK


1 Answers

def /(p);

method name is '/' which receives the parameter 'p'

p[0] == ?/

check if the string starts with a '/'. Question mark is used to specify that the character is being used literally. You can also consider it same as '/'

p[0] == ?/ ? exp1:exp2

The second question mark is for conditional evaluation. If the expression(p[0] == ?/) is true then evaluate exp1 else evaluate exp2.

So in the above case if the string parameter starts with a '/' then return the value @root + p, that is prepend it with root. On the other if the parameter does not start with a '/' then return it as such.

like image 93
randomuser Avatar answered Jan 26 '26 01:01

randomuser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!