I want to define the class variable test, threshold
so that I can use  Order.test, Order.threshold in my Rails app
but I can not access the class variable when using the rails console
I must misunderstand something, where's the problem? Thanks.
class Order < ActiveRecord::Base
  @@test=123
  @@threshold = {
    VIP: 500,
    PLATINUM: 20000
  }
Here is the rails console
irb(main):001:0> Order.class_variables
=> [:@@test, :@@threshold]
irb(main):002:0> Order.test
NoMethodError: private method `test' called for #<Class:0x007fe5a63ac738>
                How do you access a variable from another method in Python? Use the object attribute syntax to access a variable outside of a function. In a function named func , use the syntax func. variable = value to store value in variable as an attribute of func .
Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Defining a class variable A class variable looks like this: @@variable_name . Just like an instance or a local variable, you can set it equal to any type of data.
Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.
Do this:
class Order < ActiveRecord::Base
   cattr_reader :test, :threshold
   self.test = 123
   self.threshold = {
     VIP: 500,
     PLATINUM: 20000
   }
end  
Order.test
Or I'd use constants:
class Order < ActiveRecord::Base
   TEST = 123
end
Order::TEST
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With