Search code examples
rubysyntaxcamping

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


Solution

  • 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.