Ruby/Rails:class_eval 不想评估此代码

发布于 2024-12-27 09:08:55 字数 783 浏览 1 评论 0原文

为了生成 Omniauth 的模拟,我将此方法添加到 config/environments/development.rb 中,

  def provides_mocks_for(*providers)
    providers.each do |provider|
      class_eval %Q{
        OmniAuth.config.add_mock(provider, {
          :uid => '123456',
          :provider => provider,
          :nickname => 'nickname',
          :info => {
            'email' => "#{provider}@webs.com",
            'name' => 'full_name_' + provider
          }
        })
      }
    end
  end

然后在同一个文件中调用:

provides_mocks_for :facebook, :twitter, :github, :meetup

但我得到:

3.1.3/lib/active_support/core_ext/kernel/singleton_class.rb:11:in `class_eval': can't create instance of singleton class (TypeError)

To generate mocks for Omniauth, I Added this method to config/environments/development.rb

  def provides_mocks_for(*providers)
    providers.each do |provider|
      class_eval %Q{
        OmniAuth.config.add_mock(provider, {
          :uid => '123456',
          :provider => provider,
          :nickname => 'nickname',
          :info => {
            'email' => "#{provider}@webs.com",
            'name' => 'full_name_' + provider
          }
        })
      }
    end
  end

then I call in the same file:

provides_mocks_for :facebook, :twitter, :github, :meetup

But I get:

3.1.3/lib/active_support/core_ext/kernel/singleton_class.rb:11:in `class_eval': can't create instance of singleton class (TypeError)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就像说晚安 2025-01-03 09:08:55

class_evalmodule_eval (等效)用于评估字符串并立即将其作为 Ruby 代码执行。因此,它们可以用作元编程工具来动态创建方法。一个例子是

class Foo
  %w[foo bar].each do |name|
    self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{name}
        puts '#{name}'
      end
    RUBY
  end
end

它将创建两个方法 foobar 来打印它们各自的值。如您所见,我创建了一个包含函数实际源代码的字符串,并将其传递给 class_eval

虽然这是执行动态创建的代码的非常强大的工具,但必须非常小心地使用它。如果您在这里犯了错误,就会发生不好的事情™。例如,如果您在生成代码时使用用户提供的值,请确保变量仅包含您期望的值。基于 Eval 的函数通常应作为最后的手段使用。

一个更干净且通常首选的变体是使用 define_method ,如下所示:(

class Foo
  %w[foo bar].each do |name|
    define_method name do
      puts name
    end
  end
end

请注意,使用 eval 变体,MRI 会快一点。但与增加的安全性相比,这在大多数情况下并不重要和清晰度。)

现在,在给定的代码中,您可以有效地将代码写入可以直接运行的字符串中。此处使用 class_eval 会导致字符串在最顶层对象(本例中为 Kernel)的上下文中执行。由于这是一个特殊的单例对象,无法实例化(类似于 nil、true 和 false),因此您会收到此错误。

但是,当您创建直接可执行代码时,您根本不需要使用 class_eval (或任何形式的 eval)。只需按原样循环运行您的代码即可。永远记住:元编程变体(其中 eval 方法是最糟糕的)只能作为最后的手段。

class_evaland module_eval (which are equivalent) are used to evaluate and immediately execute strings as Ruby code. As such they can be used as a meta-programming facility to dynamically create methods. An example is

class Foo
  %w[foo bar].each do |name|
    self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{name}
        puts '#{name}'
      end
    RUBY
  end
end

It will create two methods foo and bar which print their respective values. As you can see, I create a string containing the actual source code of the function and pass it into class_eval.

While this is a very capable instrument of executing dynamically created code, it must be used with great care. If you make errors here, BAD THINGS WILL HAPPEN™. E.g. if you use user-supplied values when generating code, make really sure the variables contain only values you expect. Eval-based function should generally be used as the last resort.

A cleaner and generally preferred variant is to use define_method like so:

class Foo
  %w[foo bar].each do |name|
    define_method name do
      puts name
    end
  end
end

(Note that MRI is a wee bit faster with the eval variant. But that doesn't matter most of the time when compared to the added safety and clarity.)

Now in your given code, you effectively write code into a string that can be run directly. Using class_eval here leads to the string being executed in the context of the top-most object (Kernel in this case). As this is a special singleton object which can't be instanciated (similar to nil, true and false), you get this error.

However, as you create directly executable code, you don't need to use class_eval (or any form of eval) at all. Just run your code in a loop as is. And always remember: meta-programming variants (of which the eval methods are among the most bad-ass) should only be used as the last resort.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文