Ruby mixins -- getting & setting base class' class variables -


what's best way of setting class variables in base class? consider following code snippet, defining cachemixin used activerecord models. each model, want able define table storing cached data. there better way without using class_variable_set , class_variable_get ?

require 'rubygems' require 'active_support/concern'  module cachemixin     extend activesupport::concern      module classmethods         def with_cache_table(table)             self.class_variable_set('@@cache_table', table)         end     end      def fetch_data         puts self.class.class_variable_get('@@cache_table')     end  end  class testclass     include cachemixin     with_cache_table("my_cache_table") end 

since using rails, i'd recommend checking out class_attribute method.

if want without rails, i'd suggest setting instance variable directly on class object rather using class variables (which considered bad news).

class foo   class << self     attr_accessor :bar   end end  foo.bar = 'hi' p foo.bar #=> 'hi' 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -