1

目前我在我的事件模型中

class Event < ActiveRecord::Base  

   def self.cattr_accessor_with_default(name, value = nil)
     cattr_accessor name
     self.send("#{name}=", value) if value
   end
   cattr_accessor_with_default :fixed_start_end_times, false
   ...

正如我定义的调度程序模块

 class Event < ActiveRecord::Base
    include Scheduler

看来我无法将 cattr_accessor_with_default 方法移动到此调度程序模块中

module Scheduler
  def self.included(base)
    base.send :include, InstanceMethods
    base.extend ClassMethods
  end

  module ClassMethods
    def cattr_accessor_with_default(name, value = nil)
      cattr_accessor name
      self.send("#{name}=", value) if value
     end
    cattr_accessor_with_default :fixed_start_end_times, false
    ...

引发错误:Scheduler::ClassMethods:Module (NoMethodError) 的未定义方法“cattr_accessor_with_default”

我也尝试使用更好的 Rails3 方式

 module Scheduler
  def self.included(base)
    base.send :include, InstanceMethods
    base.extend ClassMethods
  end
  module ClassMethods
   class_attribute :fixed_start_end_times
   self.fixed_start_end_times = false

Scheduler::ClassMethods:Module 的相同错误未定义方法“class_attribute”

4

2 回答 2

2

我想你放cattr_accessor_with_default错地方了。试试下面的代码:

module Scheduler
  def self.included(base)
    base.send :include, InstanceMethods
    base.extend ClassMethods
    base.class_eval do
      cattr_accessor_with_default :fixed_start_end_times, false
    end
  end

  module ClassMethods
    def cattr_accessor_with_default(name, value = nil)
      cattr_accessor name
      self.send("#{name}=", value) if value
    end
    ...

这种方式cattr_accessor_with_default被发送到包含类,例如class Event,并cattr_accessor_with_default已作为类方法添加到该类中。

于 2012-12-08T14:05:50.640 回答
0

首先我创建了:

#lib/scheduler.rb

module Scheduler

  extend ActiveSupport::Concern

  included do
    class_attribute :fixed_start_end_times
    self.fixed_start_end_times = false
  end

  # adding instance methods here
  def foo
     "foo"
  end

  # adding static(class) methods here
  module ClassMethods

      def starting_on(start_date)
        where("CAST( starts_at AS TIME) = ?", Event.db_time(start_date))
      end
  end
end

# including the extension 
ActiveRecord::Base.send(:include, Scheduler)

然后我补充说:

in #config/initializers/scheduler.rb
 require "scheduler"

等等...

于 2012-12-08T14:14:57.137 回答