I'm working on a rack web app from the ground up in Ruby and I want to be able to share th开发者_开发知识库e instances of several objects across all classes in the app. For example, the logger, the request information, a currently authenticated user, get/post parameters, etc.
To any of you familiar with PHP, I've accomplished this in the past with static variables, e.g. self::$params which gets shared across every instance of every class that inherits from the base class.
What's going to be the best way to accomplish this with ruby?
the syntax is similar in ruby
$variable = value
the $ is the 'global' accessibility modifier in ruby. any code in your app that uses $variable
will be accessing the variable data.
alternatively (my preferred method), you can use a class level method:
class MyClass
def self.logger
@logger
end
end
then you can access this anywhere in your app using MyClass.logger
and third, you can specify a Constant as any value you want (as long as you don't want to change the value later).
MyContant = myvalue
anything that starts with a capital letter is a constant.
精彩评论