ns_service_pack 0.0.19 → 0.0.21

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,148 +1,154 @@
1
1
  #coding: utf-8
2
2
  =begin
3
3
  字段映射,业务字段-数据库字段对应
4
+
5
+ TODO: 不需做字段转换的处理
4
6
  =end
5
7
  require 'fileutils'
6
- module FieldMapping
7
- def self.included(base)
8
- base.extend(ClassMethods)
9
- end
10
-
11
- #在将model转成json数据时会自动调用该方法
12
- def as_json(options={})
13
- #获取数据库属性数据
14
- #TODO 想到的一个改进点:数据库查的时候根据mapping来选字段,而非全查出来,影响效率,影响较大,先不改!
15
- default_attrs = self.class.buz_hashize(self.attributes)
16
- #支持自定义方法的传入 20111118 for gao
17
- add_virtual_buz_attributes!(default_attrs)
18
- end
19
-
20
- #TODO check add some notes
21
- def add_virtual_buz_attributes!(db_buz_attrs = {})
22
- the_mapping = self.class.mapping
23
- #获取非数据库属性,称为业务虚拟属性
24
- delta_attrs = the_mapping.keys - db_buz_attrs.keys
25
- delta_attrs.each do |key|
26
- method_name = the_mapping[key]
27
- db_buz_attrs[key] = if self.respond_to?(method_name)
28
- self.send(method_name)
29
- else
30
- self.class.get_map_value(key, nil)#给出默认实现
31
- end
8
+ module Ns
9
+ module FieldMapping
10
+ def self.included(base)
11
+ base.extend(ClassMethods)
32
12
  end
33
- db_buz_attrs
34
- end
35
13
 
36
- def update_from_buz(params={})
37
- update_attributes(self.class.db_hashize(params))
38
- end
39
-
40
- module ClassMethods
41
- #Fix a bug on 20111117 by shang, this override the original method name
42
- def __model_clazz_name
43
- self.name.underscore
44
- end
45
- def model_key
46
- "#{__model_clazz_name}_mapping"
14
+ #在将model转成json数据时会自动调用该方法
15
+ def as_json(options={})
16
+ #获取数据库属性数据
17
+ #TODO 想到的一个改进点:数据库查的时候根据mapping来选字段,而非全查出来,影响效率,影响较大,先不改!
18
+ default_attrs = self.class.buz_hashize(self.attributes)
19
+ #支持自定义方法的传入 20111118 for gao
20
+ add_virtual_buz_attributes!(default_attrs)
47
21
  end
48
22
 
49
- def mapping
50
- GlobalConst.send(model_key)
23
+ # 将对象转成json数据时,允许添加额外的属性字段,但并不存入数据库
24
+ def add_virtual_buz_attributes!(db_buz_attrs = {})
25
+ the_mapping = self.class.mapping
26
+ #获取非数据库属性,称为业务虚拟属性
27
+ delta_attrs = the_mapping.keys - db_buz_attrs.keys
28
+ delta_attrs.each do |key|
29
+ method_name = the_mapping[key]
30
+ db_buz_attrs[key] = if self.respond_to?(method_name)
31
+ self.send(method_name)
32
+ else
33
+ self.class.get_map_value(key, nil)#给出默认实现
34
+ end
35
+ end
36
+ db_buz_attrs
51
37
  end
52
38
 
53
- def get_map_value(k, value)
54
- #raise "Not implemented!"
55
- #提供默认处理 #TODO 根据数据类型做些更好的转换
56
- case k
57
- when :created_at, :updated_at
58
- value.try(:to_s, :db)
59
- else
60
- value
61
- end
39
+ def update_from_buz(params={})
40
+ update_attributes(self.class.db_hashize(params))
62
41
  end
63
42
 
64
- def dump_new(force=true)
65
- if defined?(Rails)
66
- file = "#{Rails.root}/data/#{model_key}_#{Time.now.to_i}.yml"
67
- path = File.dirname(file)
68
- FileUtils.mkpath(path) unless File.directory?(path)
69
- existed = File.exists?(file)
70
- if existed
71
- puts "Warning: #{file} has existed! check it! Default override it!"
43
+ module ClassMethods
44
+ #Fix a bug on 20111117 by shang, this override the original method name
45
+ def __model_clazz_name
46
+ self.name.underscore
47
+ end
48
+ def model_key
49
+ "#{__model_clazz_name}_mapping"
50
+ end
51
+
52
+ def mapping
53
+ GlobalConst.send(model_key)
54
+ end
55
+
56
+ def get_map_value(k, value)
57
+ #raise "Not implemented!"
58
+ #提供默认处理 #TODO 根据数据类型做些更好的转换
59
+ case k
60
+ when :created_at, :updated_at
61
+ value.try(:to_s, :db)
62
+ else
63
+ value
72
64
  end
73
- if !existed || force
74
- File.open(file, 'w+') do |f|
75
- f.puts YAML.dump(buz_hashize)
65
+ end
66
+
67
+ def dump_new(force=true)
68
+ if defined?(Rails)
69
+ file = "#{Rails.root}/data/#{model_key}.yml.#{Time.now.to_i}"
70
+ path = File.dirname(file)
71
+ FileUtils.mkpath(path) unless File.directory?(path)
72
+ existed = File.exists?(file)
73
+ if existed
74
+ puts "Warning: #{file} has existed! check it! Default override it!"
75
+ end
76
+ if !existed || force
77
+ File.open(file, 'w+') do |f|
78
+ f.puts YAML.dump(buz_hashize)
79
+ end
76
80
  end
77
81
  end
78
82
  end
79
- end
80
-
81
- #辅助方法
82
- def new_from_buz(params = {})
83
- new(db_hashize(params))
84
- end
85
- def create_from_buz(params = {})
86
- create(db_hashize(params))
87
- end
88
-
89
- #生成field mapping,dump到指定的yaml文件中
90
- def dump_mapping(attr_prefix = nil, force = true)
91
- if defined?(Rails)
92
- file = "#{Rails.root}/#{GlobalConst::APP_CODE_HASHES}mappings/#{model_key}_#{Time.now.to_i}.yml"
93
- path = File.dirname(file)
94
- FileUtils.mkpath(path) unless File.directory?(path)
95
- existed = File.exists?(file)
96
- if existed
97
- puts "Warning: #{file} has existed! check it! Default override it!"
98
- end
99
- if !existed || force
100
- #获取数据库字段列表,屏蔽掉自动维护的created_at/updated_at,也可在生成的文件中配上
101
- keys = new.attributes.symbolize_keys.keys.delete_if{|k| k =~ /^created_at|updated_at$/}
102
- h = keys.inject({}) do |r, k|
103
- #移除掉表前缀
104
- rm_prefix = attr_prefix.nil? ? "#{__model_clazz_name}_" : attr_prefix
105
- new_key = k.to_s.sub(rm_prefix, '').to_sym
106
- r[new_key] = k
107
- r
83
+
84
+ #辅助方法
85
+ def new_from_buz(params = {})
86
+ new(db_hashize(params))
87
+ end
88
+ def create_from_buz(params = {})
89
+ create(db_hashize(params))
90
+ end
91
+
92
+ #生成field mapping,dump到指定的yaml文件中
93
+ def dump_mapping(attr_prefix = nil, force = true, with_timestamp = false)
94
+ file = nil
95
+ if defined?(Rails)
96
+ tstamp = with_timestamp ? ".#{Time.now.to_i}" : ""
97
+ file = "#{Rails.root}/#{GlobalConst::APP_CODE_HASHES}mappings/#{model_key}.yml#{tstamp}"
98
+ path = File.dirname(file)
99
+ FileUtils.mkpath(path) unless File.directory?(path)
100
+ existed = File.exists?(file)
101
+ if existed
102
+ puts "Warning: #{file} has existed! check it! Default override it!"
108
103
  end
109
- FileUtils.rm_f(file) if existed
110
- File.open(file, 'w+') do |f|
111
- f.puts YAML.dump(model_key.to_sym=>h)
104
+ if !existed || force
105
+ #获取数据库字段列表,屏蔽掉自动维护的created_at/updated_at,也可在生成的文件中配上
106
+ keys = new.attributes.symbolize_keys.keys.delete_if{|k| k =~ /^created_at|updated_at$/}
107
+ h = keys.inject({}) do |r, k|
108
+ #移除掉表前缀
109
+ rm_prefix = attr_prefix.nil? ? "#{__model_clazz_name}_" : attr_prefix
110
+ new_key = k.to_s.sub(rm_prefix, '').to_sym
111
+ r[new_key] = k
112
+ r
113
+ end
114
+ FileUtils.rm_f(file) if existed
115
+ File.open(file, 'w+') do |f|
116
+ f.puts YAML.dump(model_key.to_sym=>h)
117
+ end
112
118
  end
113
- puts "==>gen new file #{file} ..."
119
+ file
114
120
  end
115
121
  end
116
- end
117
122
 
118
- #TODO
119
- def dump_field_map(force=true)
120
- puts "==Warning: please use dump_mapping instead, this will be removed..."
121
- dump_mapping(nil, true)
122
- end
123
-
124
- #业务层到数据层字段参数转换并做一定值处理
125
- def db_hashize(params = {})
126
- new_params = params.symbolize_keys
127
- common_keys = new_params.keys & mapping.keys
128
- common_keys.inject({}) do |result, key|
129
- result[mapping[key]] = get_map_value(key, new_params[key])
130
- result
123
+ #TODO
124
+ def dump_field_map(force=true)
125
+ puts "==Warning: please use dump_mapping instead, this will be removed..."
126
+ dump_mapping(nil, true)
131
127
  end
132
- end
133
-
134
- #将数据层表示转成业务层表示
135
- def buz_hashize(attrs = {})
136
- #return {} if attrs.blank?
137
- #获取默认初始值
138
- attrs = new.attributes if attrs.blank?
139
- new_attrs = attrs.symbolize_keys
140
- invert_maps = mapping.invert_data
141
- common_db_attrs = new_attrs.keys & invert_maps.keys
142
- common_db_attrs.inject({}) do |result, attr|
143
- buz_field = invert_maps[attr]
144
- result[buz_field] = get_map_value(buz_field, new_attrs[attr])
145
- result
128
+
129
+ #业务层到数据层字段参数转换并做一定值处理
130
+ def db_hashize(params = {})
131
+ new_params = params.symbolize_keys
132
+ common_keys = new_params.keys & mapping.keys
133
+ common_keys.inject({}) do |result, key|
134
+ result[mapping[key]] = get_map_value(key, new_params[key])
135
+ result
136
+ end
137
+ end
138
+
139
+ #将数据层表示转成业务层表示
140
+ def buz_hashize(attrs = {})
141
+ #return {} if attrs.blank?
142
+ #获取默认初始值
143
+ attrs = new.attributes if attrs.blank?
144
+ new_attrs = attrs.symbolize_keys
145
+ invert_maps = mapping.invert_data
146
+ common_db_attrs = new_attrs.keys & invert_maps.keys
147
+ common_db_attrs.inject({}) do |result, attr|
148
+ buz_field = invert_maps[attr]
149
+ result[buz_field] = get_map_value(buz_field, new_attrs[attr])
150
+ result
151
+ end
146
152
  end
147
153
  end
148
154
  end
@@ -6,7 +6,6 @@
6
6
  =end
7
7
  require 'fileutils'
8
8
  module GlobalConst
9
- SAMPLE_FILE = "templates/code_hashes/code_hash.yml.sample"
10
9
  APP_CODE_HASHES = "config/code_hashes/"
11
10
 
12
11
  mattr_accessor :global_data
@@ -18,7 +17,7 @@ module GlobalConst
18
17
  raise "Method name: #{method_name}(#{args.inspect}) is not defined!"
19
18
  end
20
19
 
21
- def self.load_code_hashes!(hash_or_file = SAMPLE_FILE)
20
+ def self.load_code_hashes!(hash_or_file = {})
22
21
  if hash_or_file.is_a?(Hash)
23
22
  h = hash_or_file
24
23
  else
@@ -49,39 +48,4 @@ module GlobalConst
49
48
  end
50
49
  end
51
50
  end
52
-
53
- #为引用项目生成样例文件, TODO rake方式生成
54
- def self.setup_sample(yml_file = "#{APP_CODE_HASHES}code_hash.yml.sample")
55
- if defined? Rails
56
- target = "#{Rails.root}/#{yml_file}"
57
- unless File.exists?(target)
58
- path = File.dirname(target)
59
- FileUtils.mkpath(path)
60
- #默认覆盖已有
61
- FileUtils.cp(SAMPLE_FILE, target)
62
- end
63
- end
64
- end
65
-
66
- #将一个hash和array写入data下的yaml结构中
67
- def self.yamlize(hash_or_array = {}, file_name = nil)
68
- return if hash_or_array.nil?
69
- hash = if hash_or_array.is_a?(Array)
70
- hash_or_array.inject({}) do |r, k|
71
- r[k] = nil
72
- r
73
- end
74
- else
75
- hash_or_array
76
- end
77
-
78
- method_key = file_name.nil? ? "hash" : file_name.to_s
79
- name = "#{method_key}_#{Time.now.to_i}"
80
- file = "#{Rails.root}/data/#{name}.yml"
81
- path = File.dirname(file)
82
- Fileutils.mkpath(path) unless File.directory?(path)
83
- File.open(file, 'w+') do |f|
84
- f.puts YAML.dump(method_key.to_sym=>hash)
85
- end
86
- end
87
51
  end
@@ -0,0 +1,21 @@
1
+ #coding: utf-8
2
+
3
+ module Ns
4
+ #TODO 封装在gem包中
5
+ class Result
6
+ STATUSES = [:ok, :imperfect, :illegal, :error]
7
+ attr_accessor :status, :msg, :data, :errors
8
+ def initialize(params = {})
9
+ _params = params.symbolize_keys
10
+ @status = _params[:status]
11
+ @msg = _params[:msg]
12
+ @data = _params[:data]
13
+ @errors = _params[:errors]
14
+ end
15
+
16
+ def ok?
17
+ status == 'ok'
18
+ end
19
+ end
20
+ end
21
+
@@ -0,0 +1,17 @@
1
+ #coding: utf-8
2
+
3
+ module Ns
4
+ class ResultError < RuntimeError
5
+ attr_reader :result
6
+ def initialize(result = nil)
7
+ raise "Invalid result argument!" unless result.is_a?(Result)
8
+ super(result.msg)
9
+ @result = result
10
+ end
11
+
12
+ def to_s
13
+ "RusultError: #{@result.status} #{@result.msg}, detail: #{@result.errors.inspect}"
14
+ end
15
+ end
16
+ end
17
+
@@ -0,0 +1,30 @@
1
+ #coding: utf-8
2
+ module Ns
3
+ class ServiceConfig
4
+ SERVICE_CONFIG_FILE = 'config/ns_services.yml'
5
+ cattr_accessor :services
6
+ @@services = {}
7
+
8
+ def self.load_services!(config_file = SERVICE_CONFIG_FILE)
9
+ return unless File.exists?(config_file)
10
+ service_configs = YAML.load(File.read(SERVICE_CONFIG_FILE))
11
+ @@services.merge!(service_configs[Rails.env])
12
+ #load common parts if exists
13
+ if (common_parts = service_configs['common']).is_a?(Hash)
14
+ common_parts.each do |k, v|
15
+ @@services[k] = if v.is_a?(Array)
16
+ if v.size == 2
17
+ v[0] = @@services[v[0].to_sym]
18
+ Util.concat_url(v[0], v[1])
19
+ else
20
+ raise "Invalid path!"
21
+ end #/if
22
+ else
23
+ v
24
+ end #/if
25
+ end #/do
26
+ end #/if
27
+ @@services
28
+ end #/def
29
+ end
30
+ end
@@ -0,0 +1,36 @@
1
+ #coding: utf-8
2
+ require 'fileutils'
3
+ module Ns
4
+ module Util
5
+ extend self
6
+ def concat_url(prefix_url='', url='')
7
+ prefix_url = prefix_url.to_s
8
+ sep = (prefix_url[-1, 1] == '/' || url[0, 1] == '/') ? '' : '/'
9
+ "#{prefix_url}#{sep}#{url}"
10
+ end
11
+
12
+ #将一个hash和array写入data下的yaml结构中
13
+ def self.yamlize(hash_or_array = {}, file_name = nil)
14
+ return if hash_or_array.nil?
15
+ hash = if hash_or_array.is_a?(Array)
16
+ hash_or_array.inject({}) do |r, k|
17
+ r[k] = nil
18
+ r
19
+ end
20
+ else
21
+ hash_or_array
22
+ end
23
+
24
+ method_key = file_name.nil? ? "hash" : file_name.to_s
25
+ name = "#{method_key}_#{Time.now.to_i}"
26
+ file = "#{Rails.root}/data/#{name}.yml"
27
+ path = File.dirname(file)
28
+ FileUtils.mkpath(path) unless File.directory?(path)
29
+ File.open(file, 'w+') do |f|
30
+ f.puts YAML.dump(method_key.to_sym=>hash)
31
+ end
32
+ puts "Generate a yaml file in #{file}"
33
+ file
34
+ end
35
+ end
36
+ end
@@ -1,4 +1,5 @@
1
1
  #coding: utf-8
2
2
  module NsServicePack
3
+ puts "Warnign: TODO USE JEWELER DEFAULT VERSION MECHANISM NOW!"
3
4
  VERSION = '0.0.16'
4
5
  end
@@ -4,26 +4,23 @@
4
4
  #$LOAD_PATH.unshift("#{NS_GEM_ROOT}/lib")
5
5
 
6
6
  require 'fileutils'
7
+ require 'ns_service_pack/util'
7
8
  require 'ns_service_pack/code_hash'
8
9
  require 'ns_service_pack/global_const'
9
10
  require 'ns_service_pack/field_mapping'
11
+ require 'ns_service_pack/result'
12
+ require 'ns_service_pack/result_error'
10
13
  require 'ns_service_pack/result_packer'
11
- require 'ns_service_pack/application_controller_module'
14
+ require 'ns_service_pack/controller_servicable'
15
+ require 'ns_service_pack/client'
16
+ require 'ns_service_pack/service_config'
17
+ # TODO FOR optimize
12
18
 
13
- module NsServicePack
14
-
15
- PRE_INIT_FILE = "config/initializers/ns_service_pack.rb"
16
- INIT_FILE_TMPL = "templates/initializers/ns_service_pack.rb"
17
- #初始安装设置
18
- def self.install
19
- init_file = "#{Rails.root}/#{PRE_INIT_FILE}"
20
- unless File.exists?(init_file)
21
- FileUtils.cp(INIT_FILE_TMPL, init_file)
22
- puts "==>I have installed a intializer file: #{init_file}"
23
- GlobalConst.setup_sample
24
- puts "==>Now config your constants in folder: #{GlobalConst::APP_CODE_HASHES}"
25
- else
26
- puts "==>It seems you have installed ns service pack, happy with it or bug report to caory!"
27
- end
19
+ # customize deeply TODO
20
+ module Ns
21
+ class Railtie < Rails::Railtie
22
+ config.app_generators do |g|
23
+ g.templates.unshift File::expand_path('../templates', __FILE__)
24
+ end
28
25
  end
29
- end
26
+ end
@@ -0,0 +1,9 @@
1
+ #encoding: utf-8
2
+ <% module_namespacing do -%>
3
+ class <%= class_name %> < <%= parent_class_name.classify %>
4
+ <% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
5
+ belongs_to :<%= attribute.name %>
6
+ <% end -%>
7
+ include Ns::FieldMapping
8
+ end
9
+ <% end -%>
@@ -0,0 +1,44 @@
1
+ # Oracle/OCI 8i, 9, 10g
2
+ #
3
+ # Requires Ruby/OCI8:
4
+ # http://rubyforge.org/projects/ruby-oci8/
5
+ #
6
+ # Specify your database using any valid connection syntax, such as a
7
+ # tnsnames.ora service name, or an SQL connect string of the form:
8
+ #
9
+ # //host:[port][/service name]
10
+ #
11
+ # By default prefetch_rows (OCI_ATTR_PREFETCH_ROWS) is set to 100. And
12
+ # until true bind variables are supported, cursor_sharing is set by default
13
+ # to 'similar'. Both can be changed in the configuration below; the defaults
14
+ # are equivalent to specifying:
15
+ #
16
+ # prefetch_rows: 100
17
+ # cursor_sharing: similar
18
+ #
19
+
20
+ development:
21
+ adapter: mysql2
22
+ encoding: utf8
23
+ reconnect: false
24
+ pool: 5
25
+ host: localhost
26
+ database: ningshangOracle
27
+ username: root
28
+ password: root
29
+ socket: /var/run/mysqld/mysqld.sock
30
+
31
+ # Warning: The database defined as "test" will be erased and
32
+ # re-generated from your development database when you run "rake".
33
+ # Do not set this db to the same as development or production.
34
+ test:
35
+ adapter: oracle_enhanced
36
+ database: oradb.ningshang.me/ningshang
37
+ username: xxx
38
+ password: utf8
39
+
40
+ production:
41
+ adapter: oracle_enhanced
42
+ database: oradb.ningshang.me/ningshang
43
+ username: xxx
44
+ password: utf8
@@ -0,0 +1,8 @@
1
+ #coding: utf-8
2
+
3
+ #导入项目中使用的CodeHashes
4
+ GlobalConst.load_app_code_hashes!
5
+
6
+ #加载外部services依赖
7
+ NsServices = Ns::ServiceConfig.load_services!
8
+
@@ -0,0 +1,21 @@
1
+ #encoding: utf-8
2
+ #If you want to change Oracle enhanced adapter default settings then create initializer file e.g. config/initializers/oracle.rb specify there necessary defaults, e.g.:
3
+
4
+ # It is recommended to set time zone in TZ environment variable so that the same timezone will be used by Ruby and by Oracle session
5
+ #ENV['TZ'] = 'UTC'
6
+
7
+ if defined?(ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter)
8
+ ActiveSupport.on_load(:active_record) do
9
+ ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.class_eval do
10
+ # id columns and columns which end with _id will always be converted to integers
11
+ #self.emulate_integers_by_column_name = true
12
+ # DATE columns which include "date" in name will be converted to Date, otherwise to Time
13
+ #self.emulate_dates_by_column_name = true
14
+ # true and false will be stored as 'Y' and 'N'
15
+ #self.emulate_booleans_from_strings = true
16
+ # start primary key sequences from 1 (and not 10000) and take just one next value in each session
17
+ self.default_sequence_start_value = "1"# NOCACHE INCREMach ENT BY 1"
18
+ # other settings ...
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,19 @@
1
+ #coding: utf-8
2
+
3
+ #依赖的服务配置,注意:key不能重复哦!!!
4
+
5
+ #==依赖于运行环境的设置
6
+ development:
7
+ :customer_service_base_url: http://localhost:5000
8
+
9
+ test:
10
+ :customer_service_base_url: http://customer.api.ilining.cn
11
+
12
+ production:
13
+ :customer_service_base_url: http://customer.api.ilining.cn
14
+
15
+ #==依赖于前面值的共有设置
16
+ #如:开发模式下, AppConfig.services[:customers]==>http://localhost:5000/customers
17
+ #语法: 键: [依赖键(字符串形式), 附加字串]
18
+ common:
19
+ :customers: [customer_service_base_url, customers]
@@ -0,0 +1,9 @@
1
+ #encoding: utf-8
2
+ <% module_namespacing do -%>
3
+ class <%= controller_class_name %>Controller < ApplicationController
4
+ include Ns::ControllerServicable
5
+ def model_class
6
+ <%= class_name %>
7
+ end
8
+ end
9
+ <% end -%>