Ruby on rails 为自定义行为添加类方法
我想在调用Ruby on rails 为自定义行为添加类方法,ruby-on-rails,ruby-on-rails-4,activesupport-concern,Ruby On Rails,Ruby On Rails 4,Activesupport Concern,我想在调用acts\u asmethod时动态添加类方法。我的文件结构如下所示(取自): 我只想在类调用充当\u foo时才能声明类方法。实例方法与LocalInstanceMethods一起使用。最简单的方法是将插件添加到模块中,但我的其他所有类也都有此方法。我已经尝试将define\u方法添加到acts\u as方法中,返回未定义的方法。有什么想法吗?我认为您只需要创建第二个子模块,并使用extend而不是include module ActsAsFoo extend ActiveSup
acts\u as
method时动态添加类方法。我的文件结构如下所示(取自):
我只想在类调用
充当\u foo
时才能声明类方法。实例方法与LocalInstanceMethods
一起使用。最简单的方法是将插件添加到模块中,但我的其他所有类也都有此方法。我已经尝试将define\u方法
添加到acts\u as
方法中,返回未定义的方法。有什么想法吗?我认为您只需要创建第二个子模块,并使用extend
而不是include
module ActsAsFoo
extend ActiveSupport::Concern
included do
end
module ClassMethods
def acts_as_foo(options = {})
extend ActsAsFoo::LocalClassMethods
end
end
module LocalClassMethods
def class_method
# class method definition
end
end
end
class Bar
acts_as_foo
end
是否要将类方法或实例方法添加到
栏
?你的问题是类方法,但模块名为LocalInstanceMethods
@Slicedpan我不清楚。我重写了我的问题。我可以添加本地实例,但不能添加类方法。
module ActsAsFoo
extend ActiveSupport::Concern
included do
end
module ClassMethods
def acts_as_foo(options = {})
extend ActsAsFoo::LocalClassMethods
end
end
module LocalClassMethods
def class_method
# class method definition
end
end
end
class Bar
acts_as_foo
end