What would a default getter and setter look like in rails?

不羁岁月 提交于 2019-11-28 20:23:30

attr_accessor is a built-in Ruby method and has no special meaning in the context ActiveRecord. attr_accessor :tag_list is basically equivalent to this code:

# getter
def tag_list
  @tag_list
end

# setter
def tag_list=(val)
  @tag_list = val
end

In ActiveRecord models, however, it could be that you want something like this:

def tag_list
  self[:tag_list]
end

def tag_list=(val)
  self[:tag_list] = val
end

There is a slight difference: With the first method, obj[:tag_list] doesn't use the same storage as your getter and setter. With the latter, it does.

Explanation of the getter/setter concept

In Ruby, the following two lines of code are equivalent

thing.blabla
thing.blabla()

Both call the method blabla of the object thing and evaluate to the last expression evaluated within that method. This means, you also don't need a return statement in the case of the above getter method, because the method simply returns the last expression in the method (@tag_list, the value of the instance variable).

Also, those two lines of code are equivalent:

thing.blabla=("abc")
thing.blabla = "abc"

Both call the method blabla= of the object thing. The special name with the = character can be used like any other method name.

The fact that attributes, as they are sometimes called, are in fact plain methods, you can also use some special logic transformed on the values before returning or accepting them. Example:

def price_in_dollar
  @price_in_euro * 0.78597815
end

def price_in_dollar=(val)
  @price_in_euro = val / 0.78597815
end

When using ActiveRecord, this is the equivalent getter and setter versions:

def tag_list
  read_attribute(:tag_list)
end

def tag_list=(val)
  write_attribute(:tag_list, val)
end

Is this what you were looking for?

Notice the code below is in the [Helpers] path. Helpers are now included for                            
all [Controllers] to work from when instantiated.

module SettergettersHelper

#TODO Wayne 
mattr_accessor :nameport
#TODO Wayne Mattingly the code below was replaced BY ABOVE 
#TODO and not depricatable RAILS 4.2.3

# def nameport
#   @nameport 
# end

# def nameport=(nameport)
#   @nameport = nameport 
#end
end

*Getter from Accounts Controller:*
def index
   @portfolio_name = nameport     
end
*Setter from Portfolio Controller:*
def show
    @portfolio_name = @portfolio_name.portfolio_name #from database call
    SettergettersHelper.nameport =  @portfolio_name # set attribute
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!