我在每个模型中都有 4 个常用功能:
#Returns TRUE or FALSE depending on whether the column could be null or not
def self.null?(column)
columns_hash[column].null
end
#Custom delete function to change a state (deleted is a field)
def custom_delete
deleted = true
save
end
def str_created_at(format = "%d/%m/%Y %I:%M %p")
return created_at.in_time_zone.strftime(format)
end
def str_updated_at(format = "%d/%m/%Y %I:%M %p")
return updated_at.in_time_zone.strftime(format)
end
我试图将这 4 个函数(其中 1 个是抽象的:null?)移动到一个没有运气的模块:
#config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]
#app/models/post.rb
class Post < ActiveRecord::Base
include BaseModel
default_scope where(:deleted => false)
end
#lib/base_model.rb
module BaseModel
def self.included(base)
base.extend ClassMethods
end
module InstanceMethods
def custom_delete
deleted = true
save
end
def str_created_at(format = "%d/%m/%Y %I:%M %p")
return created_at.in_time_zone.strftime(format)
end
def str_updated_at(format = "%d/%m/%Y %I:%M %p")
return updated_at.in_time_zone.strftime(format)
end
end
module ClassMethods
include BaseModel::InstanceMethods
def self.null?(column)
columns_hash[column].null
end
end
end
在 Rails 控制台中:
> Post.null?("title")
> NoMethodError: undefined method 'null?' for #<Class:0x3f075c0>
> post = Post.first
> post.str_created_at
> NoMethodError: undefined method 'str_created_at' for #<Post:0x2975190>
有没有办法让这些功能正常工作?我在 Stackoverflow 上找到了这段代码,但似乎没有用,至少 Rails3 没有
我希望有可能只用 1 行添加这些功能:包括 BaseModel
所以我也可以将它添加到其他模型中。