rails魔术字段的实现 ,alias_method_chain用法,for classmethod

Encapsulates the common pattern of:

alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature

With this, you simply do:

alias_method_chain :foo, :feature
替我们定义了两个方法:foo_with_feature 和 foo_without_feature <保存原来的foo方法>
def foo_with_feature
在此添加想向foo方法里面写的代码
foo_without_feature 调用一下原来的方法
end


And both aliases are set up for you.

Query and bang methods (foo?, foo!) keep the same punctuation:

alias_method_chain :foo?, :feature

is equivalent to

alias_method :foo_without_feature?, :foo?
alias_method :foo?, :foo_with_feature?

so you can safely chain foo, foo?, and foo! with the same feature.

module ActiveRecord
# Active Record automatically timestamps create and update operations if the table has fields
# named created_at/created_on or updated_at/updated_on.
#
# Timestamping can be turned off by setting
# <tt>ActiveRecord::Base.record_timestamps = false</tt>
#
# Timestamps are in the local timezone by default but can use UTC by setting
# <tt>ActiveRecord::Base.default_timezone = :utc</tt>
module Timestamp
def self.included(base) #:nodoc:
base.alias_method_chain :create, :timestamps
base.alias_method_chain :update, :timestamps
值得注意的是 :create , :update 这两个方法均为实例方法,它和类方法 :create ,:update 重名,但最终类方法也要去掉实例的:create 和 :update方法。

这里并不是把实例方法用别名定义为类方法。 再说也不可能把实例方法定义为类方法

base.class_inheritable_accessor :record_timestamps, :instance_writer => false
base.record_timestamps = true
end

private
def create_with_timestamps #:nodoc:
if record_timestamps
t = self.class.default_timezone == :utc ? Time.now.utc : Time.now
write_attribute('created_at', t) if respond_to?(:created_at) && created_at.nil?
write_attribute('created_on', t) if respond_to?(:created_on) && created_on.nil?

write_attribute('updated_at', t) if respond_to?(:updated_at)
write_attribute('updated_on', t) if respond_to?(:updated_on)
end
create_without_timestamps
end

def update_with_timestamps #:nodoc:
if record_timestamps
t = self.class.default_timezone == :utc ? Time.now.utc : Time.now
write_attribute('updated_at', t) if respond_to?(:updated_at)
write_attribute('updated_on', t) if respond_to?(:updated_on)
end
update_without_timestamps
end
end
end



alias_method_chain 用于类方法
重新定义 ActiveRecord::Base.find方法,加上特定的查询


module FooBar

def self.included(base)
base.extend ClassMethods
base.class_eval do
class << self
alias_method_chain :find, :creator
end
end
end

module ClassMethods

def find_with_creator(*args)
if self.columns.include?('creator')
with_scope(:find => {:conditions=> [sql_str, value_hash] }) do
find_without_creator(*args)
end
end
else
find_without_creator(*args)
end

end

end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值