Understanding Ruby Refinements and Lexical Scope

If you've never used Ruby's refinements, you might be surprised to learn that they're lexically scoped. We'll discuss what this means, and the implications for your code.

If you never use refinements before, you're probably in for a surprise. You may have heard that refinements were introduced to replace monkey patching. So you might expect that you'd be able to implement something like ActiveSupport's hours method:

module TimeExtension
  refine Fixnum do
    def hours
      self * 60
    end
  end
end

class MyFramework
  using TimeExtension
end

class MyApp < MyFramework
  def index
    1.hours
  end
end

MyApp.new.index # undefined method `hours' for 1:Fixnum (NoMethodError)

If you were to run the code above, you would find that it doesn't work. So what gives?

Like so many other great ideas, the original concept of refinements had to be tweaked in order to make it work with cold hard reality.

The surprising behavior in the code that we looked at above is caused by one of these tweaks. Specifically, the rule that says that refinements are lexically scoped.

What is lexical scoping?

When we say that something is lexical, it means that has to do with text — the code on the screen as opposed to what that code means.

If two lines are lexically scoped, it simply means that they occur within the same code block — regardless of what that code block may evaluate to.

It's much easier to see an example than to talk about it:

class B
  # x and y share the same lexical scope
  x = 1
  y = 1
end

class B
  # z has a different lexical scope from x and y, even though it's in the same class. 
  z = 3
end

Refinements are lexically scoped

When we apply a refinement with the using keyword, the refinement is only visible within the lexical scope.

Here's an example showing what I mean:

module TimeExtension
  refine Fixnum do
    def hours
      self * 60
    end
  end
end

class MyApp
  using TimeExtension
  def index
    1.hours
  end
end

class MyApp
  def show
    2.hours
  end
end

MyApp.new.show # undefined method `hour' for 1:Fixnum (NoMethodError)

Even though both the index and show methods are part of the same class, only the index method has access to the refinement, because only it shares lexical scope with the using statement.

This probably seems a little bit weird, because pretty much everything else in Ruby is dynamically scoped. When you add a method to a class, the method stays there when you exit the class definition. But that's not how refinements work.

This is a number of consequences that may not be obvious at first.

You can't dynamically invoke a refinement method

Because the send method isn't defined within the same code block that contains your using statement, it can't see the refinement.

So this doesn't work:

class MyApp
  using TimeExtension
  def index
    1.send(:hours)
  end
end

You can't query the existence of a refinement method

The respond_to? method isn't within the same code block either. So it doesn't work for the same reason the send method doesn't.

class MyApp
  using TimeExtension
  def index
    1.respond_to?(:hours)
  end
end

Conclusion

I hope this clears up some of the confusion that I've seen people have around refinements. They're definitely a potentially useful feature of Ruby, but if you've never used them before they can be a little bit tricky.

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial