ns_service_pack 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
File without changes
data/README ADDED
File without changes
data/Rakefile ADDED
File without changes
@@ -0,0 +1,20 @@
1
+ #coding: utf-8
2
+
3
+ #CodeHash数据格式规则:
4
+ #访问方法名(应是合法方法名)
5
+ # 键: 值
6
+ #
7
+ #数据被输送到GlobalConst命名空间下,通过如下方式访问:
8
+ #GlobalConst.genders['男'] =>0
9
+ #GlobalConst.genders[0] =>'男'
10
+ #GlobalConst.genders[key_or_value_var] =>value_or_key
11
+
12
+ genders:
13
+ 男: 0
14
+ 女: 1
15
+ 保密: 2
16
+
17
+ booleans:
18
+ 是: true
19
+ 否: false
20
+
@@ -0,0 +1,5 @@
1
+ #coding: utf-8
2
+
3
+ #导入项目中使用的CodeHashes
4
+ GlobalConst.load_app_code_hashes!
5
+
@@ -0,0 +1,80 @@
1
+ #coding: utf-8
2
+ module ApplicationControllerModule
3
+ def index
4
+ @conds ||= {}
5
+ #TODO 添加默认搜索行为
6
+ result = paginate(model_class, @conds, params)
7
+ render :json=>ResultPacker.data(result.as_json)
8
+ end
9
+
10
+ #分页方法
11
+ def paginate(base_class=nil, conds={}, params={})
12
+ #TODO
13
+ raise "参数无效!" unless base_class.superclass == ActiveRecord::Base
14
+ page_num = params[:current_page].to_i
15
+ page_num = page_num < 1 ? 1 : page_num
16
+ page_size = params[:page_size].to_i
17
+ page_size = page_size <= 0 ? 10 : page_size
18
+ page_size = page_size > 250 ? 250 : page_size
19
+ offset = (page_num-1)*page_size
20
+
21
+ total_count = base_class.count(conds)
22
+ conds.merge!(:limit=>page_size,
23
+ :offset=>offset,
24
+ :order=>params[:order])
25
+
26
+ new_conds = conds #yield conds
27
+ #添加select子句 TODO
28
+ page_data = base_class.all(new_conds)
29
+ {
30
+ :total_size=>total_count,
31
+ :page_size=>page_size,
32
+ :current_page=>page_num,
33
+ :page_from=>offset + 1,
34
+ :page_to=>offset + page_data.size,
35
+ :page_items=>page_data
36
+ }
37
+ end
38
+ #查找单条记录
39
+ def show
40
+ result = model_class.find(params[:id])
41
+ render :json=>ResultPacker.data(result.as_json)
42
+ end
43
+
44
+ #创建记录
45
+ def create
46
+ c = model_class.new_from_buz(params[:data])
47
+ if c.save
48
+ render :json=>ResultPacker.data(c)
49
+ else
50
+ render :json=>ResultPacker.help(valid_errors(model_class.buz_hashize(c.errors.to_hash)))
51
+ end
52
+ end
53
+
54
+ #更新记录
55
+ def update
56
+ c = model_class.find(params[:id])
57
+ if c.update_from_buz(params[:data])
58
+ render :json=>ResultPacker.data(c)
59
+ else
60
+ render :json=>ResultPacker.help(valid_errors(model_class.buz_hashize(c.errors.to_hash)))
61
+ end
62
+ end
63
+
64
+ #验证错误回传
65
+ def valid_errors(error_hash={})
66
+ (error_hash||{}).each{|k, v| error_hash[k] = v.join(', ') if v.is_a? Array }
67
+ end
68
+
69
+ #ABORTED NOW
70
+ def query_fields
71
+ data = model_class.field_maps.keys.inject({}){|result, k| result[k]=nil; result}
72
+ #model_class.new.attributes #初始值问题 TODO
73
+ render :json=>ResultPacker.data(:fields=>data)
74
+ end
75
+
76
+ #动态查看该模块发布接口列表
77
+ def interfaces
78
+ @routes = Rails.application.routes.routes
79
+ end
80
+ end
@@ -0,0 +1,47 @@
1
+ #coding: utf-8
2
+ =begin
3
+ 用一致化方法根据key查值或反查,使用hash方法([]),如
4
+ code_hash = CodeHash.new({'普通会员'=>0, '高级会员'=>10})
5
+ code_hash['普通会员'] #=>0
6
+ dode_hash[0] #=>'普通会员'
7
+
8
+ 相关概念:
9
+ key: 人可识别的编码,如‘普通会员’
10
+ value: 存入数据库的编码,一般为增加数据检索速度
11
+
12
+ 规则:
13
+ * 键/值具有唯一性(符合大部分使用情况)
14
+ * 字符串键统一用字符串访问,而非符号,如code_hash['a'], not code_hash[:a] (因为很多键为汉字)
15
+ =end
16
+ class CodeHash
17
+ attr_accessor :data, :invert_data
18
+
19
+ def initialize(code_hash={})
20
+ @data = code_hash
21
+ @invert_data = code_hash.invert
22
+ end
23
+
24
+ def [](code)
25
+ #Fix a bug on 20111115
26
+ #@data[code] || @invert_data[code]||"真的没找到呀![code=#{code.to_s}]"
27
+ if @data.key?(code)
28
+ @data[code]
29
+ elsif @invert_data.key?(code)
30
+ @invert_data[code]
31
+ else
32
+ "注意:没找到对应键[#{code.to_s}]的值!"
33
+ end
34
+ end
35
+
36
+ def all
37
+ @data.merge(@invert_data)
38
+ end
39
+
40
+ def keys
41
+ @data.keys
42
+ end
43
+
44
+ def values
45
+ @data.values
46
+ end
47
+ end
@@ -0,0 +1,37 @@
1
+ #coding: utf-8
2
+ =begin
3
+ 用一致化方法根据key查值或反查,使用hash方法([]),如
4
+ code_hash = CodeHash.new({'普通会员'=>0, '高级会员'=>10})
5
+ code_hash['普通会员'] #=>0
6
+ dode_hash[0] #=>'普通会员'
7
+ 相关概念:
8
+ key: 人可识别的编码,如‘普通会员’
9
+ value: 存入数据库的编码,一般为增加数据检索速度
10
+
11
+ 规则:
12
+ * 键/值具有唯一性(符合大部分使用情况)
13
+ =end
14
+ class CodeHash
15
+ attr_accessor :data, :invert_data
16
+
17
+ def initialize(code_hash={})
18
+ @data = code_hash
19
+ @invert_data = code_hash.invert
20
+ end
21
+
22
+ def [](code)
23
+ @data[code] || @invert_data[code]||"真的没找到呀![code=#{code.to_s}]"
24
+ end
25
+
26
+ def all
27
+ @data.merge(@invert_data)
28
+ end
29
+
30
+ def keys
31
+ @data.keys
32
+ end
33
+
34
+ def values
35
+ @data.values
36
+ end
37
+ end
@@ -0,0 +1,70 @@
1
+ #coding: utf-8
2
+ =begin
3
+ 字段映射,业务字段-数据库字段对应
4
+ =end
5
+ module FieldMapping
6
+ def self.included(base)
7
+ #TODO 条件检查
8
+ base.extend(ClassMethods)
9
+ end
10
+
11
+ def as_json(options={})
12
+ self.class.buz_hashize(self.attributes)
13
+ end
14
+
15
+ def update_from_buz(params={})
16
+ update_attributes(self.class.db_hashize(params))
17
+ end
18
+
19
+ module ClassMethods
20
+ def new_from_buz(params={})
21
+ new(db_hashize(params))
22
+ end
23
+
24
+ def create_from_buz(params={})
25
+ create(db_hashize(params))
26
+ end
27
+
28
+ #TODO 在包装类提供此方法,可在include前检查
29
+ def field_maps
30
+ raise "Not implemented!"
31
+ end
32
+
33
+ def inspect_fields
34
+ puts "#buz fields\t\t#db fields\t\t #the rules"
35
+ field_maps.each do |k, v|
36
+ puts "#{k}\t\t #{v} "
37
+ end
38
+ end
39
+
40
+ def get_map_value(k, value)
41
+ #raise "Not implemented!"
42
+ value
43
+ end
44
+
45
+ #业务层到数据层字段的转换
46
+ def db_hashize(params={})
47
+ new_params = params.symbolize_keys
48
+ common_keys = new_params.keys & field_maps.keys
49
+ common_keys.inject({}) do |r, e|
50
+ r[field_maps[e]] = get_map_value(e, new_params[e])
51
+ r
52
+ end
53
+ end
54
+
55
+ #转成业务层key表示
56
+ def buz_hashize(attrs={})
57
+ #return {} if attrs.blank?
58
+ #获取默认初始值
59
+ attrs = new.attributes if attrs.blank?
60
+ new_attrs = attrs.symbolize_keys
61
+ invert_maps = field_maps.invert
62
+ common_db_attrs = new_attrs.keys & invert_maps.keys
63
+ common_db_attrs.inject({}) do |r, da|
64
+ ba = invert_maps[da]
65
+ r[ba]=get_map_value(ba, new_attrs[da])
66
+ r
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,62 @@
1
+ #coding: utf-8
2
+ =begin
3
+ * 20111115 find bug
4
+ 避免每次重新生成CodeHash的对象
5
+ * TODO 在项目中要分自己用的还是提供给外边的
6
+ =end
7
+ require 'fileutils'
8
+ module GlobalConst
9
+ SAMPLE_FILE = "#{NS_GEM_ROOT}/config/code_hashes.yml.sample"
10
+ APP_CODE_HASHES = "config/code_hashes/"
11
+
12
+ mattr_accessor :global_data
13
+ @@global_data = {}
14
+
15
+ def self.method_missing(method_name, *args, &block)
16
+ ms = method_name.to_sym
17
+ return @@global_data[ms] if @@global_data.key?(ms)
18
+ raise "Method name: #{method_name}(#{args.inspect}) is not defined!"
19
+ end
20
+
21
+ def self.load_code_hashes!(hash_or_file = SAMPLE_FILE)
22
+ if hash_or_file.is_a?(Hash)
23
+ h = hash_or_file
24
+ else
25
+ h = YAML.load(File.open(hash_or_file))
26
+ end
27
+ nh = h.symbolize_keys
28
+ nh.keys.each do |k|
29
+ if @@global_data.key?(k)
30
+ puts "==>Warning: new value(#{nh[k]}) is set for key:#{k}!"
31
+ end
32
+ @@global_data[k] = CodeHash.new(nh[k])
33
+ end
34
+ end
35
+
36
+ def self.load_app_code_hashes!(dir = APP_CODE_HASHES)
37
+ if defined? Rails
38
+ target = "#{Rails.root}/#{APP_CODE_HASHES}"
39
+ if File.directory?(target)
40
+ hfiles = Dir.glob("#{target}**/*.yml")
41
+ hfiles.each do |f|
42
+ puts "==>loading: #{f} ..."
43
+ load_code_hashes!(f)
44
+ end
45
+ end
46
+ end
47
+ end
48
+
49
+ #为引用项目生成样例文件, TODO rake方式生成
50
+ def self.setup_code_hashes(yml_file = "#{APP_CODE_HASHES}/code_hashes.yml.sample")
51
+ if defined? Rails
52
+ target = "#{Rails.root}/#{yml_file}"
53
+ unless File.exists?(target)
54
+ path = File.dirname(target)
55
+ FileUtils.mkpath(path)
56
+ #默认覆盖已有
57
+ FileUtils.cp("#{NS_GEM_ROOT}/config/code_hashes.yml.sample", target)
58
+ end
59
+ end
60
+ end
61
+ end
62
+
@@ -0,0 +1,25 @@
1
+ #coding: utf-8
2
+ =begin
3
+ Service模块提供的json数据格式封装
4
+ =end
5
+ class ResultPacker
6
+ #自定义打包
7
+ def self.pack(response_hash={})
8
+ {:status=>'ok',:msg=>''}.merge!(response_hash)
9
+ end
10
+
11
+ #封装数据
12
+ def self.data(data_hash={}, msg='通信正常!')
13
+ {:status=>'ok',:msg=>msg, :data=>data_hash}
14
+ end
15
+
16
+ #前台验证错误
17
+ def self.help(hint_hash={}, msg='数据逻辑有误,请查看错误提示!')
18
+ {:status=>'illegal',:msg=>msg, :errors=>hint_hash}
19
+ end
20
+
21
+ #异常错误
22
+ def self.error(msg='通信异常,请查看出错信息!', error_hash={})
23
+ {:status=>'error',:msg=>msg, :errors=>error_hash}
24
+ end
25
+ end
@@ -0,0 +1,3 @@
1
+ module NsServicePack
2
+ VERSION = '0.0.1'
3
+ end
@@ -0,0 +1,38 @@
1
+ #coding: utf-8
2
+ NS_GEM_ROOT = File.expand_path('../..', __FILE__)
3
+ #debug this gem
4
+ #$LOAD_PATH.unshift("#{NS_GEM_ROOT}/lib")
5
+
6
+ require 'fileutils'
7
+ require 'ns_service_pack/code_hash'
8
+ require 'ns_service_pack/global_const'
9
+ require 'ns_service_pack/field_mapping'
10
+ require 'ns_service_pack/result_packer'
11
+ require 'ns_service_pack/application_controller_module'
12
+
13
+ if defined?(Rails)
14
+ #TODO 为什么不能像ActiveRecord::Base一样include,到底什么道理呢???
15
+ class ApplicationController < ActionController::Base
16
+ include ApplicationControllerModule
17
+ end
18
+ if defined?(ActiveRecord::Base)
19
+ ActiveRecord::Base.send(:include, FieldMapping)
20
+ end
21
+ end
22
+
23
+ module NsServicePack
24
+ def self.install
25
+ #添加一个初始化文件
26
+ init_file = "#{Rails.root}/config/initializers/ns_service_pack.rb"
27
+ unless File.exists?(init_file)
28
+ FileUtils.cp("#{NS_GEM_ROOT}/config/initializers/ns_service_pack.rb", init_file)
29
+ puts "==>I have installed a intializer file: #{init_file}"
30
+ GlobalConst.setup_code_hashes
31
+ puts "==>Now you can config your constants in folder: #{GlobalConst::APP_CODE_HASHES}"
32
+ else
33
+ puts "==>It seems you have installed ns service pack, happy with it or bug report to caory!"
34
+ end
35
+ end
36
+ end
37
+
38
+ puts "==>NsServicePack has installed into application, ^^caory"
@@ -0,0 +1,26 @@
1
+ ##TODO
2
+ #$LOAD_PATH.unshift("#{Dir.pwd}/lib/ns_service_pack/lib")
3
+
4
+ require 'ns_service_pack/code_hash.rb'
5
+ require 'ns_service_pack/result_packer.rb'
6
+ require 'ns_service_pack/field_mapping.rb'
7
+ require 'ns_service_pack/application_controller_module.rb'
8
+
9
+ #TODO WHY FIXME
10
+ #if defined?(ActionController::Base)
11
+ #ActionController::Base.include(ApplicationControllerModule)
12
+ # ActionController::Base.send(:include, ApplicationControllerModule)
13
+ #end
14
+ if defined?(ActiveRecord::Base)
15
+ ActiveRecord::Base.send(:include, FieldMapping)
16
+ end
17
+
18
+ GlobalConstants = {
19
+ :genders => CodeHash.new('男'=>0, '女'=>1, '保密'=>2),
20
+ :trues => CodeHash.new('是'=>true, '否'=>false)
21
+ }
22
+
23
+ #Genders = CodeHash.new('男'=>0, '女'=>1, '保密'=>2)
24
+ #Trues = CodeHash.new('是'=>true, '否'=>false)
25
+
26
+ puts "============ns service pack has installed in your application..."
@@ -0,0 +1,24 @@
1
+ require './lib/ns_service_pack/version'
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = %q{ns_service_pack}
5
+ s.version = NsServicePack::VERSION
6
+
7
+ s.authors = %w(Caory Shang Gorgeous)
8
+ s.date = Time.now.utc.strftime("%Y-%m-%d")
9
+ s.description = %q{Service package for our service lier}
10
+ s.email = %q{cao7113@gmail.com}
11
+ s.files = Dir.glob("lib/**/*") + Dir.glob("config/**/*") + [
12
+ "Gemfile",
13
+ "ns_service_pack.gemspec",
14
+ "Rakefile",
15
+ "README"
16
+ ]
17
+ s.homepage = %q{http://weibo.com/cao7113}
18
+ s.rdoc_options = ["--charset=UTF-8"]
19
+ s.require_paths = ["lib"]
20
+ s.summary = %q{common package for our service pack}
21
+ #s.test_files = Dir.glob("test/**/*")
22
+ #s.add_development_dependency(%q<shoulda>, [">= 0"])
23
+ s.add_development_dependency(%q<rails>, [">= 3.1.0"])
24
+ end
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ns_service_pack
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Caory
9
+ - Shang
10
+ - Gorgeous
11
+ autorequire:
12
+ bindir: bin
13
+ cert_chain: []
14
+ date: 2011-11-15 00:00:00.000000000Z
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: rails
18
+ requirement: &76036470 !ruby/object:Gem::Requirement
19
+ none: false
20
+ requirements:
21
+ - - ! '>='
22
+ - !ruby/object:Gem::Version
23
+ version: 3.1.0
24
+ type: :development
25
+ prerelease: false
26
+ version_requirements: *76036470
27
+ description: Service package for our service lier
28
+ email: cao7113@gmail.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - lib/ns_service_pack.rb
34
+ - lib/ns_service_pack/global_const.rb
35
+ - lib/ns_service_pack/version.rb
36
+ - lib/ns_service_pack/application_controller_module.rb
37
+ - lib/ns_service_pack/code_hash.rb~
38
+ - lib/ns_service_pack/code_hash.rb
39
+ - lib/ns_service_pack/field_mapping.rb
40
+ - lib/ns_service_pack/result_packer.rb
41
+ - lib/ns_service_pack.rb~
42
+ - config/code_hashes.yml.sample
43
+ - config/initializers/ns_service_pack.rb
44
+ - Gemfile
45
+ - ns_service_pack.gemspec
46
+ - Rakefile
47
+ - README
48
+ homepage: http://weibo.com/cao7113
49
+ licenses: []
50
+ post_install_message:
51
+ rdoc_options:
52
+ - --charset=UTF-8
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ none: false
57
+ requirements:
58
+ - - ! '>='
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubyforge_project:
69
+ rubygems_version: 1.8.10
70
+ signing_key:
71
+ specification_version: 3
72
+ summary: common package for our service pack
73
+ test_files: []