相关疑难解决方法(0)

是否有类似于继承的类#的钩子只在Ruby类定义之后触发?

#inheritedclass Foo声明之后立即调用.我想要一些只在end关闭类声明的语句之后运行的东西.

这里有一些代码来举例说明我的需求:

class Class
  def inherited m
    puts "In #inherited for #{m}"
  end
end

class Foo
  puts "In Foo"
end
puts "I really wanted to have #inherited tiggered here."


### Output:
# In #inherited for Foo
# In Foo
# I really wanted to have #inherited tiggered here.
Run Code Online (Sandbox Code Playgroud)

这样的事情存在吗?可以创建吗?我完全没有运气吗?

ruby inheritance metaprogramming class

20
推荐指数
4
解决办法
6223
查看次数

如何在Ruby类定义的末尾设置一个钩子来运行代码?

我正在构建一个插件,允许开发人员在类定义中使用简单声明向类添加各种功能(遵循正常的acts_as模式).

例如,使用插件的代码可能看起来像

class YourClass
  consumes_my_plugin option1: :value1, specific_method_to_use: :your_method
end
Run Code Online (Sandbox Code Playgroud)

我的问题出现了,因为我想错误地检查为:specific_method_to_use参数提供的值是否作为方法存在,但通常组织和加载代码的方式,该方法尚不存在.

我的插件中的代码暂时看起来像这样:

module MyPlugin
  extend ActiveSupport::Concern

  module ClassMethods
    def consumes_my_plugin(options = {})
      raise ArgumentError.new("#{options[:specific_method_to_use]} is not defined") if options[:specific_method_to_use].present? && !self.respond_to?(options[:specific_method_to_use])
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这可行:

class YourClass
  def your_method; true; end

  consumes_my_plugin option1: :value1, specific_method_to_use: :your_method
end
Run Code Online (Sandbox Code Playgroud)

但这是大多数人编写代码的方式,它不会:

class YourClass
  consumes_my_plugin option1: :value1, specific_method_to_use: :your_method

  def your_method; true; end
end
Run Code Online (Sandbox Code Playgroud)

如何在YourClass加载时失败?我希望它出错,而不是在运行时使用NoMethodError.我可以推迟执行引发ArgumentError的行,直到加载整个类,或者做一些其他聪明的事情来实现吗?

ruby plugins loading

12
推荐指数
1
解决办法
287
查看次数

标签 统计

ruby ×2

class ×1

inheritance ×1

loading ×1

metaprogramming ×1

plugins ×1