Question

How could I access each Faker method under just one namespace:

any.sentence
any.name
... other methods from Faker::xxx classes

Instead of writing:

Faker::Lorem.sentence
Faker::Name.name
...

I am using RSpec and Rails.

Was it helpful?

Solution

In order to do this, you could define your variable any which is equal to the namespaced class you want to call:

lorem = Faker::Lorem
lorem.sentence
#=> "Dignissimos eos qui doloribus quaerat sequi est corrupti error."

name = Faker::Name
name.name
#=> "Dr. Percival Ernser"

But please, consider this as a hack and not as something you should do in your code. Indeed, when someone will read you code (or you in a few months), seeing Faker::Namespace will appear as obvious. On the other hand reading name.name will lead to confusion for you will have to look for it's definition to understand what it does. Namespaces have a reason to exist and should not be overwritten to spare a few keystrokes. Hope this answers you question!

EDIT: from you comment "unify all namespaces into one". This would not be possible (at least for Faker). Indeed, different methods have the same name, but in different namespaces. For instance, Faker has an implementation of the method name both in Faker::Name and Faker::Company (which yields different results).

As a consequence, unifying namespaces would not be possible since it would lead to loosing some methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top