Picachieu
Picachieu

Reputation: 3782

Defining non-standard accessor methods using 'attr_accessor'

I'm wondering if it is possible to use attr_accessor to reference an attribute with a different name than the methods it will define. For example, I have a class GameWindow with an attribute bg_color, and I want attr_accessor to define methods background and background=. Is there any way to do this, or do I have to define the methods myself?

Upvotes: 1

Views: 141

Answers (4)

anothermh
anothermh

Reputation: 10526

Use attr_accessor in conjunction with alias_method. For example:

class Foo
  attr_accessor :bar

  alias_method :baz, :bar
  alias_method :baz=, :bar=

  def initialize
  end
end

Then verify it works as expected:

foo = Foo.new
=> #<Foo:0x00007fabb12229a0>
foo.bar = 'foobar'
=> 'foobar'
foo.baz
=> 'foobar'
foo.baz = 'barfoo'
=> 'barfoo'
foo.bar
=> 'barfoo'

Upvotes: 1

globewalldesk
globewalldesk

Reputation: 554

attr_accessor creates the instance variable (here, @bg_color; or more precisely, makes it accessible to call on the object, though as Cary and Jörg point out below, the instance variable isn't strictly created until it is assigned) and reader and writer methods named after the symbol arguments you use. If you want it to be named background, why don't you just change the name?

Upvotes: 1

spickermann
spickermann

Reputation: 106792

attr_accessor :background

is a just a simple macro that generates these two methods for you:

def background
  @background
end

def background=(value)
  @background = value
end

When you want to have a getter and a setter method with a specific name but assign the value to a variable with a different name then just write the methods yourself - for example like this:

def background
  @bg_color
end

def background=(value)
  @bg_color = value
end

Upvotes: 1

ray
ray

Reputation: 5552

You want an attr_accessor to define the methods background and background=. attr_accessor is used to define getter and setter for instance variable & method is something which return value but you cannot have setter like background= for method.

Please check with alias_attribute & alias_method.

Upvotes: 2

Related Questions