我可以在模块中插入cattr_accessor_with_default类方法吗?

时间:2012-12-08 11:51:34

标签: ruby-on-rails

目前我的活动模式

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
   ...

我定义了一个Scheduler模块

 class Event < ActiveRecord::Base
    include Scheduler

似乎我无法将cattr_accessor_with_default方法移动到此Scheduler模块中

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
    ...

引发错误: 调度程序:: ClassMethods:模块的未定义方法`cattr_accessor_with_default' (NoMethodError)

我还尝试使用更好的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

同样的错误  调度程序:: ClassMethods的未定义方法`class_attribute':模块

2 个答案:

答案 0 :(得分: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作为类方法添加到该类中。

答案 1 :(得分: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"

etvoilà...