如何访问 gem 代码中的 class 名称
How to access the class name inside the gem code
所以我正在创建一个 acts_as
类型的 gem,并且在 gem 中我想要引用包含 [=36] 的 class =],使用其名称定义方法,例如
class MyObject < ActiveRecord::Base
acts_as_whatever
end
我想使用 class 的名称从 gem 定义方法
module LocalInstanceMethods
define_method "other_#{something.name.underscore.pluralize}" do
end
end
我应该用什么代替这个 something
以便我可以创建一个名为 other_my_objects
的方法?
PS:调用 self
引用了我所在的模块,它类似于
ActsAsWhatever::LocalInstanceMethods
而self.class
是
Module
在您的模块中,您需要一个 included 实现。
module LocalInstanceMethods
def self.included(other)
class << other
define_method "other_#{self.class.name.underscore.pluralize}" do
# ...
end
end
end
end
这段代码将以other
作为该模块包含在大多数模块中时混入的模块执行。然后您打开 class 并在 上定义方法 而不是在模块上定义方法并将该方法混合到主机模块中。
好的,我明白了,@ChrisHeald 的回答接近正确,但有一个小细节搞砸了,这对我有用
module LocalInstanceMethods
def self.included(klass)
define_method "other_#{klass.name.underscore.pluralize}" do
end
end
end
class < klass
部分将 self
和 klass
变量混淆在一起,现在没有它 klass
是我想要的实际模型,所以 klass.name
returns 我想要为我的方法定义的字符串。
我也花了一段时间才注意到这是 def self.included
而不是 included do
块,那部分搞砸了我所有的测试。
所以我正在创建一个 acts_as
类型的 gem,并且在 gem 中我想要引用包含 [=36] 的 class =],使用其名称定义方法,例如
class MyObject < ActiveRecord::Base
acts_as_whatever
end
我想使用 class 的名称从 gem 定义方法
module LocalInstanceMethods
define_method "other_#{something.name.underscore.pluralize}" do
end
end
我应该用什么代替这个 something
以便我可以创建一个名为 other_my_objects
的方法?
PS:调用 self
引用了我所在的模块,它类似于
ActsAsWhatever::LocalInstanceMethods
而self.class
是
Module
在您的模块中,您需要一个 included 实现。
module LocalInstanceMethods
def self.included(other)
class << other
define_method "other_#{self.class.name.underscore.pluralize}" do
# ...
end
end
end
end
这段代码将以other
作为该模块包含在大多数模块中时混入的模块执行。然后您打开 class 并在 上定义方法 而不是在模块上定义方法并将该方法混合到主机模块中。
好的,我明白了,@ChrisHeald 的回答接近正确,但有一个小细节搞砸了,这对我有用
module LocalInstanceMethods
def self.included(klass)
define_method "other_#{klass.name.underscore.pluralize}" do
end
end
end
class < klass
部分将 self
和 klass
变量混淆在一起,现在没有它 klass
是我想要的实际模型,所以 klass.name
returns 我想要为我的方法定义的字符串。
我也花了一段时间才注意到这是 def self.included
而不是 included do
块,那部分搞砸了我所有的测试。