Donato
Donato

Reputation: 2777

Making invalid method names valid

I remember watching a Dave Thomas Ruby tutorial where he used a technique to make invalid method names still acceptable to the interpreter. For example, even though "case date" is an invalid method name since there is a space, in the tutorial his trick allowed that method to still work.

Unfortunately, I don't remember it, but this is my situation. I accept user input and convert it to a method, as shown:

def self.define_field(name, type)
  class_eval <<-EOS
    field :#{ name}, type: #{type}
  EOS
end

The problem is if there is a space in the user input or another invalid character for a method name, I get the following error:

syntax error, unexpected tIDENTIFIER, expecting end-of-input
        field :damage date, type: Date

How can I can allow for my dynamic method creation, yet allow users to enter any input they want?

Upvotes: 0

Views: 188

Answers (2)

Shoe
Shoe

Reputation: 76240

Given your class X, you can generate a symbol that accepts the space character:

s = input.to_sym

and then call, for example, define_singleton_method on your class to define a singleton method:

X.define_singleton_method(s) do
    ...
end

And then you can use send to call that method on a class X's instance x:

x.send(input.to_sym [, args...])

Upvotes: 1

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You could try converting name to a symbol directly, not through eval.

[1] pry(main)> "damage date".to_sym
=> :"damage date"

But unless you have a real solid reason to need spaces, I would find another way. Just seems like a recipe for disaster.

No idea what Dave Thomas was talking about, but I wonder if he was discussing method_missing?

http://www.ruby-doc.org/core-2.1.5/BasicObject.html#method-i-method_missing

Upvotes: 1

Related Questions