【发布时间】:2010-11-21 20:38:24
【问题描述】:
我正在创建一个 Ruby gem,并希望使用我自己的助手扩展 ActiveRecord::Migration 以创建必要的列。 (这类似于 Devise 在为其各种身份验证策略创建迁移时所做的事情。)我意识到我添加的功能本身非常简单,并且可能有更好/更有效的方法来做到这一点 - 我正在尝试这个作为学习经验,而不是实际应用的东西。我只是想了解如何做一些像在 Rails 中添加新迁移功能这样具有侵入性的事情。
到目前为止,我已成功构建到 gem 中并安装,但是当我尝试运行如下迁移时:
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.hideable
t.tracks_hidden_at
t.timestamps
end
end
end
...它没有说没有定义可隐藏。
我研究了 Devise 的做法,我不得不承认我有点迷茫,但我试图摸索它。我做了以下事情:
用我添加的新模型扩展了 ActiveRecord,并创建了一个方法来根据我的新迁移方法应用架构更改
require 'orm_adapter/adapters/active_record'
module HiddenRecord
module Orm
# This module contains some helpers and handle schema (migrations):
#
# create_table :accounts do |t|
# t.hideable
# t.tracks_hidden_timestamp
# end
#
module ActiveRecord
module Schema
include HiddenRecord::Schema
# Tell how to apply schema methods.
def apply_hiddenrecord_schema(name, type, options={})
column name, type.to_s.downcase.to_sym, options
end
end
end
end
end
ActiveRecord::Base.extend HiddenRecord::Models
ActiveRecord::ConnectionAdapters::Table.send :include, HiddenRecord::Orm::ActiveRecord::Schema
ActiveRecord::ConnectionAdapters::TableDefinition.send :include, HiddenRecord::Orm::ActiveRecord::Schema
创建了一个类似于 Devise 的 schema.rb 的 Schema 模块,它定义了我想在迁移中使用的方法并调用一个方法来应用该模式
module HiddenRecord
# Holds schema definition for hiddenrecord model options.
module Schema
# Sets the model as having hidable rows
#
# == Options
# * :null - When true, allows the hidden row flag to be null
# * :default - Used to set default hidden status to true. If not set, default is false (rows are not hidden)
def hideable(options={})
null = options[:null] || false
default = options[:default] || false
apply_hiddenrecord_schema :hiddenrecord_is_row_hidden, Boolean, :null => null, :default => default
end
# Sets the model to record the timestamp when a row was hidden
def tracks_hidden_timestamp()
apply_hiddenrecord_schema :hiddenrecord_hidden_at, DateTime
end
end
end
为模型添加了支持新字段的方法
module HiddenRecord
module Models
# This module implements the hideable API
module Hideable
def self.included(base)
base.class_eval do
extend ClassMethods
end
end
scope :visible, where(:hiddenrecord_is_row_hidden => true)
def hidden?
return hiddenrecord_is_row_hidden || false
end
def hide
hiddenrecord_is_row_hidden = true
end
def hide!
hiddenrecord_is_row_hidden = true
save!
end
def unhide
hiddenrecord_is_row_hidden = false
end
def unhide!
hiddenrecord_is_row_hidden = false
save!
end
end
end
end
加载架构和模型文件并在 gem 的主模块中
module HiddenRecord
autoload :Schema, 'hiddenrecord/schema'
autoload :Models, 'hiddenrecord/models'
...
end
require 'hiddenrecord/models/hideable'
require 'hiddenrecord/models/tracks_hidden_timestamp'
再次,认识到这主要是一种学习体验,我希望有人能指出我如何做到这一点的正确方向。我正在 Rails 3 上尝试这个。
【问题讨论】:
-
顺便说一句,如果您在迁移中使用它来干燥代码,它可能会指出代码异味,因为您在整个数据模型中重复字段。这可能表明您应该规范化您的数据模型以减少重复。
标签: ruby-on-rails ruby activerecord