dax
dax

Reputation: 10997

How to access top-level namespace via metaprogramming in Ruby?

I can access the top-level namespace in Ruby with two colons in front of the class name, for example ::AmbiguousClass

How could I do that via metaprogramming?

I have a lot of methods (more than 5) that validate and return a given class, all of which include a line like this:

player = ::Player.find_by(uuid: input.player_uuid)

I want to make that more general so I can just pass in the class to find by uuid and cut down all those methods into one. This is what I've tried:

def validate_and_return(model_name)
  uuid_attr = "#{model_name}_uuid".to_sym
  return unless input.respond_to?(uuid_attr)
  klass = ::model_name.to_s.captialize.constantize
  instance = klass.find_by(uuid: input.send(uuid_attr))
  # validate instance
end

That doesn't work - it returns a syntax error:

Class: <SyntaxError>
Message: <"/home/dax/programming/xxx/lib/bus/converters/converter.rb:48: syntax error, unexpected tIDENTIFIER, expecting tCONSTANT

Upvotes: 2

Views: 263

Answers (2)

dax
dax

Reputation: 10997

Michael Gorman's suggestion of String Interpolation was good, this is what ended up working:

klass = "::#{model_name.to_s.capitalize}".constantize

Upvotes: 2

Michael Gorman
Michael Gorman

Reputation: 1077

You could use String Interpolation

"::#{model_name}".captialize.constantize

Upvotes: 1

Related Questions