Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Implicit and Explicit Blocks in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.36k
    Comment on it

    Blocks are basically a group of code that can be stored in a parameter and can be executed. There are majorly two ways of doing this:

     

    1) Implicit:

    In implicit, it is a nameless block and it is not passed as a parameter, it is executed using yield.

    Lets see an example suppose we want to execute some code by adding begin..rescue, so every time in every function we need to write the begin rescue like this:

    def get_country_date(id)
       begin
           ## The real code
           @country = Country.find(id)
        rescue StandardError => e
           Rails.logger.error e.message
        end
    end


    So excepting the line that finds country using id, we need to rewrite the code everyplace wherever we want to use begin..rescue. But if we use implicit version of blocking we can write the code like this:

    def get_country_data(id)
      with_rescuing { @country = Country.find(id) }
    end
    
    def with_rescuing
        begin
            ## The real code
            ## Here the calling function gets called and executed
            yield
         rescue StandardError => e
              Rails.logger.error e.message
          end
    end

     

    2) Explicit:

    In case of explicit blocking we can create a block and can give a name to it explicitly, so that whenever it is needed we can pass it as a parameter and then we can call it using that parameter

    
    def get_country_data(id)
       with_rescuing { @country = Country.find(id) }
    end
    
    def with_rescuing(&get_country_block)
        begin
            ## The real code
            ## here we can call the calling function
            get_country_block.call
         rescue StandardError => e
            Rails.logger.error e.message
         end
    end

    Thus we can see the blocks are one of the best thing in rails to remove the boilerplate code and also they solve the callback problems.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: