Question

Is there a short way to do this?

def value
   @val
end

def value=(value)
    @val = value
end
Was it helpful?

Solution

No, there is not. All attr_accessor does is define two methods, one called value (in this case) and the other called value= that set an instance variable of the same name. Since you should only be accessing the instance variable via the getter/setter methods, it shouldn't matter what it is called internally.

If you are inheriting, you can use a call to super to ensure constancy:

class Walrus
  attr_accessor :bubbles
end

class Harold < Walrus
  def bubbles
    # do Harold related things here
    super
  end

  def bubbles=(value)
    # do Harold related things here
    super(value)
  end
end

EDIT

If you really want to do it then you can define your own method on Class:

class Class
  def attr_accessor2(method_name, attribute_name)
    define_method(method_name) do
      instance_variable_get("@#{attribute_name}")
    end

    define_method("#{method_name}=") do |value|
      instance_variable_set("@#{attribute_name}", value)
    end
  end
end

I haven't tested it, but something like that should work. I'm not saying it's a good idea, but that is what you're looking for.

EDIT2

Here is how it works in practice:

1.9.3p0 :012 > class Derp
1.9.3p0 :013?>   attr_accessor2 :herp, :meep
1.9.3p0 :014?>   end
 => #<Proc:0x007fc75b02e958@(irb):7 (lambda)> 
1.9.3p0 :015 > d = Derp.new
 => #<Derp:0x007fc75b027e00> 
1.9.3p0 :016 > d.herp
 => nil 
1.9.3p0 :017 > d.herp = 10
 => 10 
1.9.3p0 :018 > d.herp
 => 10 
1.9.3p0 :019 > d.instance_variable_get("@meep")
 => 10 

OTHER TIPS

attr_accessor :val
alias_method :value, :val
alias_method :value=,:val=

If you want to block the access of the original method, you can use

remove_method :val
remove_method :val=

I don't know if you consider this shorter.

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