i'm new ruby , ruby on rails, coming background of c-like languages.
here code found in application_controller.rb
file:
def current_user @current_user ||= renter.find(session[:user_id]) if session[:user_id] end helper_method :current_user def authorize_user redirect_to '/login' unless current_user end
here don't understand it:
- on line 4, :current_user
invoking current_user
instance method, or directly accessing @current_user
instance variable?
- on line 7, current_user
invoking current_user
instance method, or directly accessing @current_user
instance variable?
- on line 2, :user_id
variable or more string literal being used key? kind of in javascript 1 might write session["user_id"]
theuser_id
property of session
object.
class methods aren't relevant in example - aren't being used here.
instance variables never call methods when get/set.
although opposite happen. it's common pattern create getter/setter methods instance variables, common attr reader/writer/accessor helpers defined in ruby core. if write attr_accessor :foo
, foo=
, foo
get/set instance variable.
but not happen default.
to answer other question:
a symbol :user_id
starts colon , similar string. difference between symbol , string may seem arbitrary, important concept in ruby , making distinction in head idea.
to respond comment:
line 4, helper_method :current_user
specific rails, consider "rails magic" if like. in effect making current_user
method callable views (whereas default available in controller). :current_user
symbol used reference current_user
method. not have understand in total detail, suffice know helper_method
takes symbol same name method , makes method available views. far i'm aware, it's relevant rails controllers.
it's common in ruby use symbols refer method names. it's more intermediate concept. can see example in send
:
def asd return 0 end class foo def instance_method_bar return 0 end def self.class_method_bar return 0 end end # how methods typically called asd foo.new.instance_method_bar foo.class_method_bar # way call them, using send send(:asd) foo.new.send(:instance_method_bar) foo.send(:class_method_bar)
i'm not recommending use send
unless need to, make more clear how symbol :current_user
being used in helper_method
line 7 current_user
method being called.
Comments
Post a Comment