class A
@@x = 2
def say
@@x
end
end
class B < A
def haha=y
@@x=y
end
end
class C < A
def haha=y
@@x=y
end
end
b = B.new
c = C.new
b.say #=> 2
c.say #=> 2
b.haha = 'because I can'
c.say #=> 'because I can'
But still,
they are useful.
Letsbe practical
And my code has no threads !
class A
@@a_variable_shared_across_all_instances_of_A = nil
def my_method
# and it is accessible within the scope
# just like that
@a_variable_shared_across_all_instances_of_A = 'shared-data'
end
end
class Shippping
@@countries = Country.all
def label_the_parcel(address)
country = @@countries.detect{|name| name == address.country_name}
print_label country.shipping_code
end
end
class Shippping
@@california_code = State.where(country: 'U.S.A').last.shipping_code
def label_for_california(address)
print_label address
print_label @@california_code
end
end
This can fail during class load
This can fail rails s
class Shippping
def label_for_california(address)
print_label address
print_label Shipping.california_code
end
def self.california_code
@@california_code ||= State.where(country: 'U.S.A').last.shipping_code
end
end
The instance-variable cache pattern
Because why not
class A
def slowly_loaded_data
@slowly_loaded_data ||= slow_queries
end
end
The actual instance-variable cache pattern
class Shippping
def label_for_california(address)
print_label address
print_label Shipping.california_code
end
@@california_code = nil
def self.california_code
@@california_code ||= State.where(country: 'U.S.A').last.shipping_code
end
end
That, right there, is a cache
And caches have to expire sometime.
Some day, the california_code will change.
So for that day, we have -
class Shippping
@@california_code = nil
def self.california_code
@@california_code ||= State.where(country: 'U.S.A').last.shipping_code
end
def self.flush_california_code
@@california_code = nil
end
end
class State
after_save :flush1
def flush1
Shipping.flush_california_cache if name=='california'
end
end
And I have no threads
What could possibly go wrong?
drum-roll...
Enter Sidekiq
cd discourse
ag @@ . | wc -l #=>
cd gitlab
ag @@ . | wc -l #=>
cd spree
ag @@ . | wc -l #=>
cd rails
ag @@ . | wc -l #=>
Thanks