Why is class_eval sometimes used when re-opening the class could work?

217 Views Asked by At

I've come across some code in a Rails app in the form of

ThirdPartyLibrary::Foo.class_eval do
  def bar?
    @bar_field == 'true'
  end
end

and I'm wondering why they didn't just do

class ThirdPartyLibrary::Foo
  def bar?
    @bar_field == 'true'
  end
end

Are there any advantages in using class_eval when there isn't anything you want to pass in to the new code?

1

There are 1 best solutions below

0
Denny Mueller On
class ThirdPartyLibrary::Foo do
  def original?
    true
  end
end

ThirdPartyLibrary::Foo.class_eval do
  def baz?
    true
  end
end

ThirdPartyLibrary::Foo.original? #=> true
ThirdPartyLibrary::Foo.baz? #=> true

class ThirdPartyLibrary::Foo
  def bar?
    true
  end
end

ThirdPartyLibrary::Foo.original? #=> undefined method
ThirdPartyLibrary::Foo.baz? #=> undefined method
ThirdPartyLibrary::Foo.bar? #=> true

class_eval 'adds' something to an existing class and your second example just defines the class new and overwrites everything that was there before. This is used for example when you want to monkeypatch or extend libraries.