<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Sohaib.io]]></title><description><![CDATA[Software Consultant]]></description><link>https://sohaib.io/</link><image><url>https://sohaib.io/favicon.png</url><title>Sohaib.io</title><link>https://sohaib.io/</link></image><generator>Ghost 5.22</generator><lastBuildDate>Tue, 07 Apr 2026 13:09:37 GMT</lastBuildDate><atom:link href="https://sohaib.io/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Issues of Control Flow logic in Respond To Blocks]]></title><description><![CDATA[<p>The following code was written by my boss to simulate an issue arising with a production app that I&apos;ve been working on at work.</p><pre><code class="language-language-ruby">class RacersController &lt; ApplicationController
  def race
    @racer = Racer.first
    @was_in_if_block, @was_outside_if_block = false, false
 
    respond_to do |format|
      if</code></pre>]]></description><link>https://sohaib.io/issues-of-control-flow-logic-in-respond-to-blocks/</link><guid isPermaLink="false">63715d5375e00a177dd89312</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 21:11:06 GMT</pubDate><content:encoded><![CDATA[<p>The following code was written by my boss to simulate an issue arising with a production app that I&apos;ve been working on at work.</p><pre><code class="language-language-ruby">class RacersController &lt; ApplicationController
  def race
    @racer = Racer.first
    @was_in_if_block, @was_outside_if_block = false, false
 
    respond_to do |format|
      if @racer.name == &apos;john&apos;
        format.json do
          render :json =&gt; @racer
          @was_in_if_block = true
          return true
        end
      end
 
      @was_outside_if_block = true
      format.json { render :json =&gt; @racer.name = &quot;foobar&quot; }
      format.html { @racer }
    end
  end
end
</code></pre><h2 id="the-problem">The Problem</h2><p>Can you identify any issues lurking within this code?</p><p>Assuming that the responses is a json response and that <code>@racer.name</code>&#x2003; is indeed &apos;john&apos;,<br>the if condition should execute which would lead one to believe that <code>@was_in_if_block</code> would evaluate to true followed by the the rest of the code not to execute.</p><p>However, if this code was spec&apos;ed out(which indeed it is, to simulate the issue, <a href="https://github.com/alisyed/RailsAnomalies">https://github.com/alisyed/RailsAnomalies</a>) we would have observed that <code>@was_outside_if_block</code> was being assigned true as well. In other words the return isn&apos;t working as expected.</p><h2 id="the-underlying-reason">The underlying reason</h2><p>Lets delve into Rails code!</p><p>The <code>respond_to</code> method invokes the important <code>retrieve_collector_from_mimes(mimes, &amp;block)</code> which first evaluates the particular type of mime_types the controller action can respond to at a controller level configuration for example:</p><pre><code>respond_to :json, :except =&gt; [ :edit ]
</code></pre><p>as well as inspecting the block passed to the respond_to method. The collector for the particular request is attempted to be found.</p><p>Assuming that the the request is JSON for our case, the collector for our particular request will initially be assigned the format.json block in the if condition(It is important to note that the code inside the actual format blocks will not be executed yet) and since another format.json block exists, our collector will later on be assigned that block. This is carried out by the block.call(collector) statement.</p><pre><code class="language-language-ruby">def respond_to(*mimes, &amp;block)
  raise ArgumentError, &quot;respond_to takes either types or a block, never both&quot; if mimes.any? &amp;&amp; block_given?
 
  if collector = retrieve_collector_from_mimes(mimes, &amp;block)
    response = collector.response
    response ? response.call : default_render({})
  end
end
 
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 267
def retrieve_collector_from_mimes(mimes=nil, &amp;block) #:nodoc:
  mimes ||= collect_mimes_from_class_level
  collector = Collector.new(mimes)
  block.call(collector) if block_given?
  format = collector.negotiate_format(request)
 
  if format
    self.content_type ||= format.to_s
    lookup_context.formats = [format.to_sym]
    lookup_context.rendered_format = lookup_context.formats.first
    collector
  else
    head :not_acceptable
    nil
  end
end
</code></pre><p>As the code in the format.json block isn&apos;t executed yet, <code>@was_in_if_block</code> will still have a value false, and the <code>@was_outside_if_block</code> will be assigned a value of true.</p><p>The format.json block will then execute, which is the last line of the respond_to method.</p>]]></content:encoded></item><item><title><![CDATA[Hacking and adding custom helpers to Ghost]]></title><description><![CDATA[<p>Deprecated. The blog post was for Ghost v0.3.2. Things have changed. Please do not try the following below</p><p><strong>Warning:</strong> The code I&apos;m about to mention below isn&apos;t a good practise. As far as I am aware, Ghost does not currently support adding custom HandleBar</p>]]></description><link>https://sohaib.io/hacking-and-adding-custom-helpers-to-ghost/</link><guid isPermaLink="false">63715ce275e00a177dd892fd</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 21:09:49 GMT</pubDate><content:encoded><![CDATA[<p>Deprecated. The blog post was for Ghost v0.3.2. Things have changed. Please do not try the following below</p><p><strong>Warning:</strong> The code I&apos;m about to mention below isn&apos;t a good practise. As far as I am aware, Ghost does not currently support adding custom HandleBar helpers but plan on doing so <a href="https://github.com/TryGhost/Ghost/tree/master/content/apps">soon.</a></p><p>I wanted to change the behavior of my blog so as to display the blog cover only on the home page and not on pages where pagination is being used(/page/2/). After a quick look at the helpers present on Ghost&apos;s <a href="http://docs.ghost.org/themes/">documentation</a> I couldn&apos;t find a suitable solution.</p><p>I started to read up on the code of Ghost. From the looks of it there are plans to add support for apps however that functionality does not exist yet. Here is the quick and dirty solution I came up with.</p><p>I added the following code in the &#xA0;<code>core/server/helpers/index.js</code> file</p><pre><code class="language-lang-javascript">coreHelpers.ifOnHomePage = function (options) {
  if ((config.paths.urlFor(this, false) === &quot;/&quot;)) {
    return options.fn(this);
  }
  return options.inverse(this);
}
</code></pre><p>followed by registering it at the end of the same file</p><pre><code class="language-lang-javascript">registerThemeHelper(&apos;ifOnHomePage&apos;, coreHelpers.ifOnHomePage);
</code></pre><p>After adding the code in, the handlebars helper can now be used.</p><pre><code class="language-lang-html">  {{#ifOnHomePage}}
    &lt;h1&gt;I work!&lt;/h1&gt;
  {{/ifOnHomePage}}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Importing dates from spreadsheets in Ruby]]></title><description><![CDATA[<p>I encountered an interesting issue yesterday. While importing data present in an xlsx file, I noticed that dates present in the excel file were being imported as numerical floats. My original code below</p><pre><code class="language-language-ruby">DATE_COL = 10
2.upto(10) do |i|
  ...
  excel_file = Excelx.new(&quot;#{Rails.root}/temp/final_</code></pre>]]></description><link>https://sohaib.io/importing-dates-from-spreadsheets-in-ruby/</link><guid isPermaLink="false">63715cb175e00a177dd892ed</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 21:08:10 GMT</pubDate><content:encoded><![CDATA[<p>I encountered an interesting issue yesterday. While importing data present in an xlsx file, I noticed that dates present in the excel file were being imported as numerical floats. My original code below</p><pre><code class="language-language-ruby">DATE_COL = 10
2.upto(10) do |i|
  ...
  excel_file = Excelx.new(&quot;#{Rails.root}/temp/final_cand/khi_counsel_list.xlsx&quot;)
  date_ar = excel_file.cell(i, DATE_COL).to_formatted_s(:long)
end
</code></pre><p>After a quick google, I found out that the float being returned was the number of days that have elapsed since (Dec 30, 1899). As to why this is the case, I have no clue and didn&apos;t look it up.</p><p>I went ahead and modified my code to the following after which everything started working fine.</p><pre><code class="language-language-ruby">date_ar = (DateTime.new(1899,12,30) + excel_file.cell(i, DATE_COL).days).to_date.to_formatted_s(:long)
</code></pre>]]></content:encoded></item><item><title><![CDATA[Interesting Rails Feature - Active Model Dirty]]></title><description><![CDATA[<p>This feature isn&apos;t used nearly as much as it deserves to be.</p><p>ActiveRecord objects keep a track of whether any of their attributes values have changed via the ActiveModel::Dirty module.</p><pre><code class="language-language-ruby"># Loading an object to memory
user = User.find 29
# changed? lets us know whether any modifications were</code></pre>]]></description><link>https://sohaib.io/interesting-rails-feature-active-model-dirty/</link><guid isPermaLink="false">637159c275e00a177dd892d8</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 20:55:38 GMT</pubDate><content:encoded><![CDATA[<p>This feature isn&apos;t used nearly as much as it deserves to be.</p><p>ActiveRecord objects keep a track of whether any of their attributes values have changed via the ActiveModel::Dirty module.</p><pre><code class="language-language-ruby"># Loading an object to memory
user = User.find 29
# changed? lets us know whether any modifications were made to the object
u.changed? # =&gt; false
# After Modifying the users name, we can see that changed? now returns a true
u.name = &apos;Frank&apos;
u.changed? # =&gt; true
# changed can be used to let us know which attributes have been modified
u.changed  # [&quot;name&quot;]
# #{attribute_name}_was can be used to obtain the former value
u.name_was # &quot;Joliene&quot;
# #{attribute_name}_change returns an array consisting of the old and new values
u.name_change # [&quot;Joliene&quot;, &quot;Frank&quot;]
</code></pre><p>Next time, when temporarily assigning variables the values of object attributes before modifying them, remember that this functionality is already provided by Rails in an elegant way.</p>]]></content:encoded></item><item><title><![CDATA[Interesting Rails Feature - Partial Counters]]></title><description><![CDATA[<p>While working on a Ruby on Rails project, I stumbled across an interesting feature.</p><pre><code class="language-language-ruby">= render partial: &apos;product_line&apos;, collection: product_lines_with_brand(@result, brand)
</code></pre><p>In my view I was rendering the partial above. For styling reasons I required that after ever second time the partial is called,</p>]]></description><link>https://sohaib.io/interesting-rails-feature-partial-counters/</link><guid isPermaLink="false">6371597475e00a177dd892cc</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 20:55:17 GMT</pubDate><content:encoded><![CDATA[<p>While working on a Ruby on Rails project, I stumbled across an interesting feature.</p><pre><code class="language-language-ruby">= render partial: &apos;product_line&apos;, collection: product_lines_with_brand(@result, brand)
</code></pre><p>In my view I was rendering the partial above. For styling reasons I required that after ever second time the partial is called, I should be adding a clearing div.</p><p>After spending some time to try to find a good solution, I stumbled upon something really neat that Rails provides by default. Every partial rendered upon a collection has a counter associated with it. In the case of the partial above, the name of the counter would be <code>product_line_counter</code>. Basically the name of the partial with <code>_counter</code> being appended to the end of it.</p><p>So all I had to do was append the following snippet of code at the very end of the partial</p><pre><code class="language-language-haml">- if product_line_counter.odd?
  .clear
</code></pre>]]></content:encoded></item><item><title><![CDATA[Classes vs Modules for Obese Models]]></title><description><![CDATA[<p>The concept of Thin controllers and fat models is preached heavily to individuals who are just picking up Rails. In my opinion the same concern should be extended to models as well. Quite often is it the case that models in a Rails app tend to get really large(1000</p>]]></description><link>https://sohaib.io/classes-vs-modules-for-obese-models/</link><guid isPermaLink="false">6371591575e00a177dd892c0</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 20:53:52 GMT</pubDate><content:encoded><![CDATA[<p>The concept of Thin controllers and fat models is preached heavily to individuals who are just picking up Rails. In my opinion the same concern should be extended to models as well. Quite often is it the case that models in a Rails app tend to get really large(1000 loc+ in same cases!). This results in a coding nightmare.</p><p>In order to have cleaner code, this issue can be addressed in multiple ways. Two of which(for a monolithic architecture) are using:</p><h2 id="modules">Modules</h2><p>A common practice is to extract a set of related methods from the model and move them to a separate module. These modules then serve as mixins to the actual model.</p><pre><code class="language-language-ruby">class User &lt; ActiveRecord::Base
  include Billing
  include RegistrationMethods
  include Subscription
  include Socials
  ...
  ...
end
</code></pre><p>The issue that I feel exists with this approach is that inferencing where a certain method is coming from tends to be quite unintuitive. The actual developer who made the modules might have no issues, however, scenarios will always exist where the rest of the dev-team will need to execute a grep command to figure out where a method is being defined.</p><h2 id="classes-ftw">Classes Ftw!</h2><p>A better approach would be to break down the functionality into smaller classes that have &#xA0;actual meaning.</p><pre><code class="language-language-ruby">class Subscription
  def initialize(user)
    @user = user
  end

  def subscribe!
    ...
  end

  def unsubscribe!
  end
end
</code></pre><p>By breaking down the functionality and collecting them into logical entities(OOP) you gain the following advantages.</p><p>No More Grep Driven Development. Reading the code becomes very intuitive. I know exactly where to look in my code base to figure out the code.</p><p>The interfaces are very clean and well-defined.</p><p>Classes can be completely independent from Rails. TDD becomes uber fast as we do not need to require the evil spec_helper(i.e. Rails).(Thank you Gary of DAS for this. You&apos;ve helped me a lot. )</p><h2 id="ending-notes">Ending Notes</h2><p>It is important to note that I&apos;m in no way saying that modules are completely useless. Though I do feel that they are overused and that Object Oriented Design is often times overlooked while working in the Rails environment.</p>]]></content:encoded></item><item><title><![CDATA[Using GraphQL, a Ruby on Rails Introduction]]></title><description><![CDATA[<p>GraphQL has been stirring up quite a buzz ever since it was introduced by Facebook. Since then companies like Github, Shopify and Pinterest have been using it as a core part of their technology stack. A typical GraphQL query would be structured as below:</p><pre><code>{
  allMovies {
    title
    description
  }
}
</code></pre><p>GraphQL provides flexibility</p>]]></description><link>https://sohaib.io/coming-soon/</link><guid isPermaLink="false">6371557f75e00a177dd89115</guid><category><![CDATA[News]]></category><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 13 Nov 2022 20:37:19 GMT</pubDate><media:content url="https://sohaib.io/content/images/2022/11/graphql.png" medium="image"/><content:encoded><![CDATA[<img src="https://sohaib.io/content/images/2022/11/graphql.png" alt="Using GraphQL, a Ruby on Rails Introduction"><p>GraphQL has been stirring up quite a buzz ever since it was introduced by Facebook. Since then companies like Github, Shopify and Pinterest have been using it as a core part of their technology stack. A typical GraphQL query would be structured as below:</p><pre><code>{
  allMovies {
    title
    description
  }
}
</code></pre><p>GraphQL provides flexibility for querying the necessary fields that are required. This flexibility provides numerous advantages over REST. Perhaps the most compelling advantage is that it eliminates over-fetching and under-fetching.</p><p>REST APIs have a fixed structure defined for each API endpoint. They either return too much data on each API call or too little. For example, if only titles need to be displayed on a certain page, returning extra fields doesn&#x2019;t make much sense. Similarly, what if we wanted to return only the distributor&#x2019;s name? In traditional REST APIs it would most probably require sending another request to fetch the distributor information for that movie.</p><p>In this post, we&#x2019;ll implement a simplistic API exposing movies and their reviews.</p><p>Setting Up</p><p>We&#x2019;ll start by setting up a base Rails project. We&#x2019;ll be using the <a href="https://github.com/rmosolgo/graphql-ruby">graph-ql</a> ruby gem.</p><pre><code>gem install bundler
gem install rails
bundle install
rails new learning-graphql
rails db:create
</code></pre><p>The Rails application should be up and running. Start the server with rails s and verify that it&#x2019;s up and running. Add the line gem &#x2018;graphql&#x2019; to the Gemfile and then run the following commands:</p><pre><code>bundle install
rails generate graphql:install
bundle install
</code></pre><p>The reason for the second bundle install is because the generator for Rails adds another gem to the Gemfile gem &#x2018;graphiql-rails&#x2019;, group: :development. We&#x2019;ll be seeing the use of this gem soon.</p><p>Now let&#x2019;s create our Movie model. Enter the following commands in the terminal:</p><pre><code>rails generate model movie title description
rails db:migrate
</code></pre><p>We can now proceed with creating dummy data. This can be done by adding some records into the db/seeds.rb file, followed by executing the rails db:seed command.</p><pre><code class="language-language-ruby">Movie.create(
  title: &#x2018;Deadly Weapon&#x2019;,
  description: &#x2018;2 retired monks walk into a bar&#x2019;
)

Movie.create(
  title: &#x2018;Deadly Weapon 2 &#x2014; This time time it&#x2019;s personal&#x2019;,
  description: &#x2018;Like Deadly Weapon, only deadlier and more personal&#x2019;
)
</code></pre><p>Fetching Movies with GraphQL</p><p>Now comes the time to create a GraphQL type to represent the schema of our Movie. This can be achieved with the aid of the generators provided by the GraphQL gem.</p><p><code>rails generate graphql:object movie</code></p><pre><code class="language-language-ruby"># In the app/graphql/types/movie_type.rb file

Types::MovieType = GraphQL::ObjectType.define do
  name &#x201C;Movie&#x201D;
  
  field :id, !types.ID
  field :title, !types.String
  field :description, types.String
end
</code></pre><p>Each schema consists of fields; discrete pieces of information that collectively represent our model. GraphQL treats all fields as nullable values by default. In our case, we know that the id and title fields will always exist. Therefore we can declare them as non-nullable fields. This is achieved by prepending ! to the type of each field.</p><p>Let&#x2019;s now create a query mapping to either fetch all the movies or a single movie based off its ID.</p><pre><code class="language-language-ruby">Types::QueryType = GraphQL::ObjectType.define do
  name &#x201C;Query&#x201D;
  # Add root-level fields here.
  # They will be entry points for queries on your schema.
  field :allMovies do
    type types[Types::MovieType]
    description &#x201C;A list of all the movies&#x201D;

    resolve -&gt; (obj, args, ctx) {
      Movie.all
    }
  end

  field :movie do
    type Types::MovieType
    description &#x201C;Return a movie&#x201D;
    argument :id, !types.ID
    resolve -&gt; (obj, args, ctx) { Movie.find(args[:id]) }
  end
end
</code></pre><p>A couple of points to observe here:<br>&#x200A;&#x2014;&#x200A;The resolve function is responsible for accepting the query payload and implementing the backend logic to fulfill the request and fetch the data required.</p><p>&#x2014; In the movie field an argument has been defined. Since this field should return a single movie we need to select a criteria to uniquely identify each movie. Utilizing the non-nullable id attribute makes the most sense.</p><p>Time to see the fruits of our hard work! Remember the gem we installed? It allows us to interact with our API via the route added in the config/routes.rb file.</p><p>The default route is /graphiql however it can be modified in the routes file. Head on over to the route and you&#x2019;ll see a page similar to the one below:</p><figure class="kg-card kg-image-card"><img src="https://sohaib.io/content/images/2022/11/graphql-ruby-viewer.png" class="kg-image" alt="Using GraphQL, a Ruby on Rails Introduction" loading="lazy" width="1600" height="920" srcset="https://sohaib.io/content/images/size/w600/2022/11/graphql-ruby-viewer.png 600w, https://sohaib.io/content/images/size/w1000/2022/11/graphql-ruby-viewer.png 1000w, https://sohaib.io/content/images/2022/11/graphql-ruby-viewer.png 1600w" sizes="(min-width: 720px) 720px"></figure><p>Let&#x2019;s now try to fetch all the movies. Enter in the following query and execute it. If all goes well, we&#x2019;ll see something to the image below. Try removing fields and seeing how the response changes.</p><pre><code>{
  allMovies {
    id
    title
    description
  }
}
</code></pre><p>To retrieve a single Movie, the following payload can be used:</p><pre><code>{
  movie(id: 2) {
    id
    title
  }
}
</code></pre><p>Note how the arguments are passed. A good practice exercise would be to try modifying allMovies to take an argument limit that restricts the number of movies in the response based off the value.</p><p>Creating a Movie<br>Until now, we&#x2019;ve only been looking at how data can be retrieved. Now we&#x2019;ll talk about using mutations for operations that modify data. Let&#x2019;s see how we can go ahead with trying to create a movie:</p><pre><code class="language-languge-ruby"># app/graphql/types/mutation_type.rb

Types::MutationType = GraphQL::ObjectType.define do
  name &quot;Mutation&quot;

  field :createMovie, Types::MovieType do
    argument :title, !types.String
    argument :description, !types.String

    resolve -&gt; (obj, args, ctx) {
      Movie.create(
        title: args[:title],
        description: args[:description]
      )
    }
  end
end
</code></pre><p>The implementation accepts two arguments, the title and the description of the movie. Invoking them has the same syntax as queries, however it&#x2019;s necessary to add the mutation keyword. The invocation below will return the ID of the newly created movie. It can be modified to return any other field as well.</p><pre><code>mutation {
  createMovie(title: &#x201C;Deadly Weapon 3&#x201D;, description: &#x201C;Even deadlier!&#x201D;) {
    id
  }
}
</code></pre><p>Adding Relationships</p><p>To try out linking different types, we need to first create a new model. For this example we&#x2019;ll be creating a Review model. A movie can have many reviews.</p><p>Enter the following commands in the terminal:</p><pre><code>rails generate model review content movie_belongs_to
rails db:migrate
rails generate graphql:object review
</code></pre><p>We&#x2019;ll also need to add has_many :reviews to the app/models/movie.rb file. Time to implement the Review type representation. While we&#x2019;re at it, we should also add an additional field in the Movie type to expose reviews as an additional property.</p><pre><code class="language-language-ruby"># app/graphql/types/review_type.rb

Types::ReviewType = GraphQL::ObjectType.define do
  name &quot;Review&quot;

  field :id, types.ID
  field :content, types.String
end
</code></pre><pre><code class="language-language-ruby"># app/graphql/types/movie_type.rb

Types::MovieType = GraphQL::ObjectType.define do
  name &quot;Movie&quot;

  field :id, types.ID
  field :title, types.String
  field :description, types.String

  field :reviews do
    type types[Types::ReviewType]
    resolve -&gt; (obj, args, ctx) {
      obj.reviews
    }
  end
end
</code></pre><p>Congratulations! Reviews have now been exposed as an additional optional field for our movies. Let&#x2019;s quickly try it out!</p><p>Proceeding Further<br>This concludes our brief look into utilizing GraphQL with Ruby.</p><p>Going through the guides at the GraphQL (<a href="http://graphql.org/learn/">http://graphql.org/learn/</a>) followed by the graphql-ruby gems (<a href="http://graphql-ruby.org/guides">http://graphql-ruby.org/guides</a>) will get you up to speed with everything that GraphQL has to offer. For practical examples of GraphQL, playing with the API of Github might also serve you well.</p>]]></content:encoded></item><item><title><![CDATA[Scoping in Ruby]]></title><description><![CDATA[<p>Around a month back, a colleague of mine and I were playing around with nesting and variable scopes in ruby. Here is a small piece of code I wrote for better understanding what is going on.</p><pre><code class="language-language-ruby">A = &apos;I am A&apos;
module Foo
  B = &apos;I am B&apos;</code></pre>]]></description><link>https://sohaib.io/scoping-in-ruby/</link><guid isPermaLink="false">63715c0f75e00a177dd892e3</guid><dc:creator><![CDATA[Sohaib Talaat Bhatti]]></dc:creator><pubDate>Sun, 02 Dec 2012 21:05:00 GMT</pubDate><content:encoded><![CDATA[<p>Around a month back, a colleague of mine and I were playing around with nesting and variable scopes in ruby. Here is a small piece of code I wrote for better understanding what is going on.</p><pre><code class="language-language-ruby">A = &apos;I am A&apos;
module Foo
  B = &apos;I am B&apos;
  puts Module.nesting.inspect
  class Bar
    C = &apos;I am C&apos;
    puts Module.nesting.inspect
    module World
      D = &apos;I am D&apos;
      puts Module.nesting.inspect
      puts ::A
      puts ::Foo::Bar::C
    end
  end
end
    
p A
p Foo::B
p Foo::Bar::C
p Foo::Bar::World::D
</code></pre><p>While not in the scope a particular variable, the <code>::</code> operator can be used to specify which scope this variable belongs to. So If we&apos;re currently outside module Foo, <code>Foo::Bar::World::D</code> can be used to access constant <code>D</code>.</p><p>The statements with a <code>::</code> right at the very start are used to set the current scope to root level. This can be observed in module world where <code>::A</code> is being used to access the constant defined outside of module Foo.</p><p>The code above generates the following output.</p><pre><code class="language-language-ruby">[Foo]
[Foo::Bar, Foo]
[Foo::Bar::World, Foo::Bar, Foo]
I am A
I am C
&quot;I am A&quot;
&quot;I am B&quot;
&quot;I am C&quot;
&quot;I am D&quot;
</code></pre><p>Oh and the nesting method is used to see the current level of nesting.</p>]]></content:encoded></item></channel></rss>