Class_eval在每个块内部不起作用

时间:2022-02-24 14:27:27

I have defined a module to extend ActiveRecord.

我已经定义了一个扩展ActiveRecord的模块。

In my case I have to generate instance methods with the symbols given as arguments to the compound_datetime class method. It works when class_eval is called outside the each block but not inside it; in the latter case I get an undefined method error.

在我的情况下,我必须使用作为compound_datetime类方法的参数给出的符号生成实例方法。当class_eval在每个块之外调用但不在其中时调用它;在后一种情况下,我得到一个未定义的方法错误。

Does anyone know what I am doing wrong?

有谁知道我做错了什么?

module DateTimeComposer
  mattr_accessor :attrs
  @@attrs = []

  module ActiveRecordExtensions
    module ClassMethods
      def compound_datetime(*attrs)
        DateTimeComposer::attrs = attrs
        include ActiveRecordExtensions::InstanceMethods
      end
    end

    module InstanceMethods
      def datetime_compounds
        DateTimeComposer::attrs
      end

      def self.define_compounds(attrs)
        attrs.each do |attr|
          class_eval <<-METHODS
            def #{attr.to_s}_to()
              puts 'tes'
            end
          METHODS
        end
      end

      define_compounds(DateTimeComposer::attrs)
    end
  end
end


class Account < ActiveRecord::Base
  compound_datetime :sales_at, :published_at
end

When I try to access the method:

当我尝试访问该方法时:

Account.new.sales_at_to

I get a MethodError: undefined method sales_at_to for #<Account:0x007fd7910235a8>.

我得到一个MethodError:未定义的方法sales_at_to for# <0x007fd7910235a8>


  

<<

<<<<>>


  

<<

<<<<>>