RubyA trick with Ruby anonymous classes
Originally published here
Since everything in Ruby is an object it is only normal that classes are objects too. Which means they just have regular constructors with initializers, as any other object would do.
What can I use it for?
Anonymous classes are an amazing candidate for testing mixings.
There's a caveat though... You need to be aware that anonymous classes have no name (they are anonymous after all ;) ) so any call to
Class.new.name will return
Classes only acquire a name when you assign them to a constant. That is:
So, if you need to test things which depend on the class name you can't use anonymous classes, although they still have a benefit over regular declarations on tests, which is that they can be assigned to variables, while regular
class...end declarations can't.
So, if you need a class with a name on a test you can still use this, only remember to remove the constant on your test's teardown.
If you're on a Rails app and use RSpec, it even has a helper to test things with anonymous controllers: https://relishapp.com/rspec/rspec-rails/v/3-9/docs/controller-specs/anonymous-controller, which is especially useful to test things like login/logout flows independently.