[英]ruby set Dynamic Class variables with mixins
我需要定義一些設置命名空間和表類變量的類變量。
這是我正在使用的混合模板:
module MyMixin
module ClassMethods
....
end
module InstanceMethods
....
end
def self.included(receiver)
namespace, table = receiver.name.underscore.pluralize.split('/')
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
對於下面的代碼,我想要命名空間的類變量:'hello'和table:'worlds'
module Hello
class World
include MyMixin
end
end
對於下面的代碼,我想要命名空間的類變量:'goodbye'和table:'friends'
module Goodbye
class Friend
include MyMixin
end
end
我嘗試使用 receiver.class_variable_set/get 但是當我加載Goodbye::Friend代碼時, Hello::World的類變量。
如何設置和分隔兩個類變量?
我意識到我可以使用 instance_variables 來為我的類保留單獨的“類”變量,這些變量是通過混合模板實例化的。
module MyMixin
module ClassMethods
....
end
module InstanceMethods
....
end
def self.included(receiver)
namespace, table = receiver.name.underscore.pluralize.split('/')
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
receiver.instance_variable_set :@namespace, namespace.to_sym
receiver.instance_variable_set :@table, table.to_sym
receiver.instance_variable_set :@properties, {}
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.