ruby on rails - Access to class instance variable -
how can read class variable? in case can't value variable.
class mediacontentscontroller < applicationcontroller @randomusrid = rand(100) def create puts @randomusrid end end
first of all, @randomusrid refers instance variable, not class variable. can access through instance of class, not direct on class. class variable, should use @@randomusrid.
what looking attr_accessor :randomusrid, through this, can read on instance method, , can set through instance of class.
here's how:
class mediacontentscontroller < applicationcontroller attr_accessor :randomusrid @randomusrid = rand(100) def create puts @randomusrid end end but @randomusrid = rand(100) won't set @randomusrid random number, @ least not recommend way. should use before_action here.
class mediacontentscontroller < applicationcontroller attr_accessor :randomusrid before_action :set_user_id_to_a_random_number, only: :create def create puts @randomusrid end private def set_user_id_to_a_random_number @randomusrid = rand(100) end end edit:
each time call set_user_id_to_a_random_number function, generate different number based on rand(100) , store inside @randomusrid. if that's not want, , want persist same value, can following:
def set_user_id_to_a_random_number @randomusrid = rand(100) unless defined? @randomusrid end edit:
what have stated works 1 request, if have multiple request, won't work. ryan bates says here:
an instance variable sticks around single request, using technique described benefit if need call method multiple times per request.
that leaves 2 options if want store between multiple requests. either can go databases, or can use called memcached.
Comments
Post a Comment