Sha256: 9457d31d9bd41ca9515f3f9e4806d103173c904c8f971c24fd3f1e232b51fd6c
Contents?: true
Size: 1.63 KB
Versions: 2
Compression:
Stored size: 1.63 KB
Contents
#coding: utf-8 =begin 字段映射,业务字段-数据库字段对应 =end module FieldMapping def self.included(base) #TODO 条件检查 base.extend(ClassMethods) end def as_json(options={}) self.class.buz_hashize(self.attributes) end def update_from_buz(params={}) update_attributes(self.class.db_hashize(params)) end module ClassMethods def new_from_buz(params={}) new(db_hashize(params)) end def create_from_buz(params={}) create(db_hashize(params)) end #TODO 在包装类提供此方法,可在include前检查 def field_maps raise "Not implemented!" end def inspect_fields puts "#buz fields\t\t#db fields\t\t #the rules" field_maps.each do |k, v| puts "#{k}\t\t #{v} " end end def get_map_value(k, value) #raise "Not implemented!" value end #业务层到数据层字段的转换 def db_hashize(params={}) new_params = params.symbolize_keys common_keys = new_params.keys & field_maps.keys common_keys.inject({}) do |r, e| r[field_maps[e]] = get_map_value(e, new_params[e]) r end end #转成业务层key表示 def buz_hashize(attrs={}) #return {} if attrs.blank? #获取默认初始值 attrs = new.attributes if attrs.blank? new_attrs = attrs.symbolize_keys invert_maps = field_maps.invert common_db_attrs = new_attrs.keys & invert_maps.keys common_db_attrs.inject({}) do |r, da| ba = invert_maps[da] r[ba]=get_map_value(ba, new_attrs[da]) r end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
ns_service_pack-0.0.2 | lib/ns_service_pack/field_mapping.rb |
ns_service_pack-0.0.1 | lib/ns_service_pack/field_mapping.rb |