tags:

views:

553

answers:

3

For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:

Object.variable_name= 'new value'

However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:

Object.send('variable.name=', 'new value')

However, I am wondering is there a way to escape the period so that I can use

Object.variable.name= 'new value'

+7  A: 

Don't do it!

Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:

attr_writer :bar
attr_reader :baz
attr_accessor :foo

Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.

class SillySetter
  def initialize path=nil
    @path = path
  end

  def method_missing name,value=nil
    new_path = @path ? "#{@path}.#{name}" : name
    if name.to_s[-1] == ?=
      puts "setting #{new_path} #{value}"
    else
      return self.class.new(path=new_path)
    end
  end
end

s = SillySetter.new
s.foo = 5              # -> setting foo= 5
s.foo.bar.baz = 4      # -> setting foo.bar.baz= 4

I didn't want to encourage ruby sillyness, but I just couldn't help myself!

Nick Retallack
A: 

If there's no hope of changing the canonical names, you could alias the getters and setters manually:

def variable_name
 send 'variable.name'
end

def variable_name=(value)
 send 'variable.name=', value
end
James A. Rosen
A: 

The only reason I can think of to do this, is if you really REALLY hate the person who is going to be maintaining this code after you.

And I don't mean 'he ran over my dog' hatred.

I mean real steaming pulsing vein in temple hatred.

So, in short, don't. :-)

fatgeekuk