strikeroff-helpful_utils 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/CHANGELOG ADDED
@@ -0,0 +1,2 @@
1
+ v0.0.1 "Add String extensions, event machine, deep clone for Hash and Array, humanized attributes and project configuration support"
2
+ v0.0.2 "Change README"
data/Manifest ADDED
@@ -0,0 +1,16 @@
1
+ CHANGELOG
2
+ gem-build.sh
3
+ heplful_utils.gemspec
4
+ Manifest
5
+ Rakefile
6
+ README
7
+ lib/helpful_utils.rb
8
+ lib/helpful_utils/activerecord_ext/humanized_attributes.rb
9
+ lib/helpful_utils/common/configuration.rb
10
+ lib/helpful_utils/core_ext/array.rb
11
+ lib/helpful_utils/core_ext/hash.rb
12
+ lib/helpful_utils/core_ext/kernel.rb
13
+ lib/helpful_utils/core_ext/string.rb
14
+ lib/helpful_utils/patching_utils/event_machine.rb
15
+ lib/helpful_utils/patching_utils/inheritance_tree.rb
16
+ test/core_tests.rb
data/README ADDED
@@ -0,0 +1,38 @@
1
+ Гем представляет собой набор полезных инструменов для повседневной работы (пока только на русском)
2
+
3
+ 1.Configuration
4
+ Загрузка конфигурационных файлов в окружение Configuration из папки RAILS_ROOT/config/project(по умолчанию).
5
+ Для каждого найденного yaml файла в папке project мы производим загрузку в окружение. Все это делается
6
+ в целях удобства обращения к конфигурации. Доступ к конфигам из проекта - Configuration.НАЗВАНИЕ_ФАЙЛА.КЛЮЧ.
7
+ 2. Расширение классов стандартной библиотеки
8
+
9
+ а) Расширение классов Array и Hash
10
+ метод deep_clone - выполняется рекурсивное клонирование всех элементов.
11
+ б) Расширение модуля Kernel
12
+ метод with - Переключение области видимости на объект.Использовать осторожно. Рекомендуется применять,
13
+ когда в коде идет несколько операций над одним объектом. Таким образом следующий код:
14
+
15
+ contexts.set_context(:region, :volga)
16
+ contexts.set_context(:site, "gionet.ru")
17
+ contexts.set_context(:special, special_object)
18
+ contexts.run
19
+
20
+ можно преобразовать в следующий:
21
+
22
+ with contexts do
23
+ set_context(:region, :volga)
24
+ set_context(:site, "gionet.ru")
25
+ set_context(:special, special_object)
26
+ run
27
+ end
28
+ в) расширения класса String
29
+ 1) метод to_json_with_russian_support - Если вызывать у строки с русским текстом стандартный метод to_json, а потом попробовать отобразить ее
30
+ то получится что то невразумительное.Данный метод исправляет проблему. Пример
31
+ "тут русский текст".to_json(:russian=>true). По умолчанию russian == false
32
+ 2) json? - Проверка,является ли строка JSON'ом
33
+ 3. Класс EventMachine
34
+ Класс служит для подписывания на события и выполнения кода по выполнении этих событий.
35
+ Пример с подписыванием на событие after_initialize можно посмотреть helpful_utils.rb
36
+ 4. Другие утилиты для падчинга можно посмотреть в helpful_utils\patching_utils
37
+ 5. Кастомные названия для полей моделей(по мотивам
38
+ http://rubybrothers.ru/2008/9/9/custom-attributes-names-for-rails-validations)
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ require "echoe"
2
+
3
+ Echoe.new( "helpful_utils" ) do |p|
4
+ p.author = [ "Ilya Vesov","Anatoly Lapshin"]
5
+ p.summary = "collection of helpful utils,hacks , etc"
6
+ p.email = "strikeroff@gmail.com"
7
+ p.url = "http://github.com/strikeroff/helpful_utils"
8
+
9
+ p.runtime_dependencies = ['activesupport']
10
+ p.development_dependencies = []
11
+
12
+ p.need_tar_gz = false
13
+ p.retain_gemspec = true
14
+ p.gemspec_name = 'heplful_utils.gemspec'
15
+ p.test_pattern = ["test/**/*_test.rb"]
16
+
17
+ p.clean_pattern.push 'lib/*-*'
18
+ p.has_rdoc = true
19
+ p.rdoc_pattern = ["README", "CHANGELOG", "lib/**/*.rb"]
20
+ p.rdoc_options << "-c utf-8"
21
+ p.ignore_pattern = [".gitignore", "doc", "examples", ".idea", "coverage.data", "*.bat"]
22
+ end
data/gem-build.sh ADDED
@@ -0,0 +1,3 @@
1
+ #!/bin/bash
2
+ rm pkg/*.gem
3
+ rake manifest && rake gem && gem install -l pkg/*.gem
@@ -0,0 +1,34 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = %q{helpful_utils}
5
+ s.version = "0.0.1"
6
+
7
+ s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
8
+ s.authors = ["Ilya Vesov, Anatoly Lapshin"]
9
+ s.date = %q{2009-09-14}
10
+ s.description = %q{collection of helpful utils,hacks , etc}
11
+ s.email = %q{strikeroff@gmail.com}
12
+ s.extra_rdoc_files = ["CHANGELOG", "README", "lib/helpful_utils.rb", "lib/helpful_utils/activerecord_ext/humanized_attributes.rb", "lib/helpful_utils/common/configuration.rb", "lib/helpful_utils/core_ext/array.rb", "lib/helpful_utils/core_ext/hash.rb", "lib/helpful_utils/core_ext/kernel.rb", "lib/helpful_utils/core_ext/string.rb", "lib/helpful_utils/patching_utils/event_machine.rb", "lib/helpful_utils/patching_utils/inheritance_tree.rb"]
13
+ s.files = ["CHANGELOG", "gem-build.sh", "heplful_utils.gemspec", "Manifest", "Rakefile", "README", "lib/helpful_utils.rb", "lib/helpful_utils/activerecord_ext/humanized_attributes.rb", "lib/helpful_utils/common/configuration.rb", "lib/helpful_utils/core_ext/array.rb", "lib/helpful_utils/core_ext/hash.rb", "lib/helpful_utils/core_ext/kernel.rb", "lib/helpful_utils/core_ext/string.rb", "lib/helpful_utils/patching_utils/event_machine.rb", "lib/helpful_utils/patching_utils/inheritance_tree.rb", "test/core_tests.rb"]
14
+ s.has_rdoc = true
15
+ s.homepage = %q{http://github.com/strikeroff/helpful_utils}
16
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Helpful_utils", "--main", "README", "-c utf-8"]
17
+ s.require_paths = ["lib"]
18
+ s.rubyforge_project = %q{helpful_utils}
19
+ s.rubygems_version = %q{1.3.1}
20
+ s.summary = %q{collection of helpful utils,hacks , etc}
21
+
22
+ if s.respond_to? :specification_version then
23
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
24
+ s.specification_version = 2
25
+
26
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
27
+ s.add_runtime_dependency(%q<activesupport>, [">= 0"])
28
+ else
29
+ s.add_dependency(%q<activesupport>, [">= 0"])
30
+ end
31
+ else
32
+ s.add_dependency(%q<activesupport>, [">= 0"])
33
+ end
34
+ end
@@ -0,0 +1,10 @@
1
+ class ActiveRecord::Base
2
+ def self.human_attribute_name(attribute_key_name)
3
+ default = attribute_key_name.humanize
4
+ if self.const_defined?('HUMANIZED_ATTRIBUTES')
5
+ self.const_get('HUMANIZED_ATTRIBUTES')[attribute_key_name.to_sym] || default
6
+ else
7
+ default
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,50 @@
1
+ class Configuration
2
+ # Загрузка конфигурационных файлов в окружение Configuration из папки RAILS_ROOT/config/project(по умолчанию).
3
+ # Для каждого найденного yaml файла в папке project мы производим загрузку в окружение.
4
+ # Все это делается в целях удобства обращения к конфигурации.
5
+ # Доступ к конфигам из проекта - Configuration.НАЗВАНИЕ_ФАЙЛА.КЛЮЧ
6
+
7
+ cattr_accessor :path_to_config_dir
8
+ @@path_to_config_dir = "#{::RAILS_ROOT}/config/project"
9
+
10
+ def self.load_configurations
11
+ if defined? ::RAILS_ROOT
12
+ Dir["#{path_to_config_dir}/*.yaml"].each do |config_file|
13
+ load_configuration_from_file(config_file)
14
+ end
15
+ end
16
+
17
+ end
18
+
19
+ def self.has?(config_name)
20
+ self.method_defined? config_name
21
+ end
22
+
23
+
24
+ def self.load_configuration_from_file ( config_file )
25
+ config = YAML.load_file( config_file )
26
+ if config.instance_of? Hash
27
+ attrs = []
28
+ config.each_key { |key| attrs << key.to_sym } # извлекаем имена полей
29
+ config_struct = Struct.new *attrs # создаем структуру с этими полями
30
+ new_config = config_struct.new # создаем объект этой структуры
31
+ config_struct.members.each do |attr_name| # инициализируем значения полей объекта
32
+ new_config.send( "#{attr_name}=", config[attr_name] )
33
+ end
34
+ config = new_config # отображаем трансформацию в конфиг
35
+ end
36
+ attr_name = File.basename( config_file, ".yaml" )
37
+
38
+ self.class_eval do
39
+ cattr_accessor attr_name.to_sym # создаем в модуле аттрибут
40
+ end
41
+
42
+ self.send("#{attr_name}=", config)
43
+ end
44
+
45
+
46
+ end
47
+
48
+
49
+ Configuration.load_configurations
50
+
@@ -0,0 +1,22 @@
1
+ module HelpfulUtils
2
+ module CoreExt
3
+ module Array
4
+ def clone_by_someway(value)
5
+ return value if value.is_a?(Symbol)
6
+ if value.respond_to?(:deep_clone)
7
+ value.deep_clone
8
+ else
9
+ value.clone
10
+ end
11
+ end
12
+
13
+ def deep_clone
14
+ self.collect{|v| clone_by_someway(v)}
15
+ end
16
+ end
17
+ end
18
+ end
19
+
20
+ class Array
21
+ include HelpfulUtils::CoreExt::Array
22
+ end
@@ -0,0 +1,27 @@
1
+ module HelpfulUtils
2
+ module CoreExt
3
+ module Hash
4
+ def deep_clone
5
+ hash = {}
6
+ self.each_pair do |key, value|
7
+ hash.merge!({clone_by_someway(key)=>clone_by_someway(value)})
8
+ end
9
+ hash
10
+ end
11
+
12
+ def clone_by_someway(value)
13
+ return value if value.is_a?(Symbol)
14
+ if value.respond_to?(:deep_clone)
15
+ value.deep_clone
16
+ else
17
+ value.clone
18
+ end
19
+ end
20
+ end
21
+
22
+ end
23
+ end
24
+
25
+ class Hash
26
+ include HelpfulUtils::CoreExt::Hash
27
+ end
@@ -0,0 +1,27 @@
1
+ module Kernel # :nodoc:
2
+ # Переключение области видимости на объект.
3
+ # Использовать осторожно. Рекоммендуется применять, когда в коде идет несколько операций
4
+ # над одним объектом. Таким образом следующий код:
5
+ #
6
+ # Gionet.contexts.set_context(:region, :volga)
7
+ # Gionet.contexts.set_context(:site, "gionet.ru")
8
+ # Gionet.contexts.set_context(:special, special_object)
9
+ # p Gionet.contexts.slice
10
+ # Gionet.contexts.run
11
+ #
12
+ # можно преобразовать в следующий:
13
+ #
14
+ # with Gionet.contexts do
15
+ # set_context(:region, :volga)
16
+ # set_context(:site, "gionet.ru")
17
+ # set_context(:special, special_object)
18
+ # p slice
19
+ # run
20
+ # end
21
+ #
22
+ # Внимание при использовании необходимо по причине того, что внутри блока происходит
23
+ # смешивание областей видимости самого объекта и окружения из которого он вызывается.
24
+ def with(object, &block)
25
+ object.instance_eval &block
26
+ end
27
+ end
@@ -0,0 +1,57 @@
1
+ module HelpfulUtils
2
+ module CoreExt
3
+ module String
4
+
5
+ module JSON
6
+ # Если вызывать у строки с русским текстом стандартный метод to_json, а потом попробовать отобразить ее
7
+ # то получится что то невразумительное.Данный метод исправляет проблему. Пример
8
+ # "тут русский текст".to_json(:russian=>true)
9
+ # по умолчанию russian == false
10
+ def to_json_with_russian_support(options = nil) #:nodoc:
11
+ result = nil
12
+ unless options.blank?
13
+ if options[:russian]== true
14
+ json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
15
+ ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
16
+ }
17
+ json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
18
+ result = json + '"'
19
+ end
20
+ end
21
+ if result.blank?
22
+ result = to_json_without_russian_support options
23
+ end
24
+ result
25
+ end
26
+
27
+ alias_method_chain :to_json, :russian_support
28
+
29
+
30
+ # Проверка,является ли строка JSON'ом
31
+ def json?
32
+ return true if !self.blank? && ActiveSupport::JSON.decode(self).is_a?(Hash)
33
+ rescue ActiveSupport::JSON::ParseError
34
+ false
35
+ end
36
+ end
37
+ module UrlHelpers
38
+ # can raise URI::InvalidURIError
39
+ # приводит строку к полноценному URL
40
+ def to_url(prefix="http://")
41
+ return nil if self.blank?
42
+ if URI.parse(self).class != URI::HTTP
43
+ "#{prefix}#{self.strip}"
44
+ else
45
+ self.dup
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+
54
+ class String
55
+ include HelpfulUtils::CoreExt::String::JSON
56
+ include HelpfulUtils::CoreExt::String::UrlHelpers
57
+ end
@@ -0,0 +1,38 @@
1
+ module HelpfulUtils
2
+ # Класс служит для подписывания на события и выполнения кода по выполнении этих событий.
3
+ # Пример с подписыванием на событие after_initialize htkmcjd
4
+ # Rails::Initializer.class_eval do
5
+ # def after_initialize_with_helpful_utils
6
+ # HelpfulUtils::EventMachine.after_initialize_with_helpful_utils
7
+ # after_initialize_without_helpful_utils
8
+ # end
9
+ #
10
+ # alias_method_chain :after_initialize, :helpful_utils
11
+ # end
12
+ #
13
+ # HelpfulUtils::EventMachine.subscribe :after_initialize_with_helpful_utils do
14
+ # require File.join(File.dirname(__FILE__), "helpful_utils", "activerecord_ext", "humanized_attributes.rb")
15
+ # end
16
+ # Feel free in use this tool,it's powerfull =)
17
+
18
+
19
+
20
+ class EventMachine
21
+ @@actions_and_blocks = {}
22
+ # cattr_accessor :actions_and_blocks
23
+ class << self
24
+ def method_missing(method_symbol, *parameters)#:nodoc:
25
+ if @@actions_and_blocks.has_key? method_symbol
26
+ @@actions_and_blocks[method_symbol].each do |action|
27
+ action.call *parameters
28
+ end
29
+ end
30
+ end
31
+
32
+ def subscribe(event_symbol, &block)
33
+ @@actions_and_blocks[event_symbol] ||= []
34
+ @@actions_and_blocks[event_symbol] << block
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,14 @@
1
+ module HelpfulUtils
2
+ module InheritanceTree
3
+ def objects
4
+ class_objects = []
5
+ ObjectSpace.each_object(self) {|e| class_objects << e }
6
+ class_objects
7
+ end
8
+
9
+ def class_children
10
+ (@class_objects ||= Class.objects).select {|e| e.superclass == self }
11
+ end
12
+ end
13
+ end
14
+ Module.send :include, HelpfulUtils::InheritanceTree
@@ -0,0 +1,26 @@
1
+ require File.join(File.dirname(__FILE__), "helpful_utils", "common", "configuration")
2
+
3
+
4
+ Dir[File.join(File.dirname(__FILE__), "helpful_utils", "patching_utils")<<"/*.rb"].each do |file|
5
+ require file
6
+ end
7
+
8
+ # Some files need to be required after iitialize
9
+ Rails::Initializer.class_eval do
10
+ def after_initialize_with_helpful_utils
11
+ HelpfulUtils::EventMachine.after_initialize_with_helpful_utils
12
+ after_initialize_without_helpful_utils
13
+ end
14
+ alias_method_chain :after_initialize, :helpful_utils
15
+ end
16
+
17
+ HelpfulUtils::EventMachine.subscribe :after_initialize_with_helpful_utils do
18
+
19
+ Dir[File.join(File.dirname(__FILE__), "helpful_utils", "core_ext")<<"/*.rb"].each do |file|
20
+ require file
21
+ end
22
+
23
+ require File.join(File.dirname(__FILE__), "helpful_utils", "activerecord_ext", "humanized_attributes.rb")
24
+
25
+
26
+ end
File without changes
metadata ADDED
@@ -0,0 +1,93 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: strikeroff-helpful_utils
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Ilya Vesov, Anatoly Lapshin
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-09-14 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: activesupport
17
+ type: :runtime
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: "0"
24
+ version:
25
+ description: collection of helpful utils,hacks , etc
26
+ email: strikeroff@gmail.com
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - CHANGELOG
33
+ - README
34
+ - lib/helpful_utils.rb
35
+ - lib/helpful_utils/activerecord_ext/humanized_attributes.rb
36
+ - lib/helpful_utils/common/configuration.rb
37
+ - lib/helpful_utils/core_ext/array.rb
38
+ - lib/helpful_utils/core_ext/hash.rb
39
+ - lib/helpful_utils/core_ext/kernel.rb
40
+ - lib/helpful_utils/core_ext/string.rb
41
+ - lib/helpful_utils/patching_utils/event_machine.rb
42
+ - lib/helpful_utils/patching_utils/inheritance_tree.rb
43
+ files:
44
+ - CHANGELOG
45
+ - gem-build.sh
46
+ - heplful_utils.gemspec
47
+ - Manifest
48
+ - Rakefile
49
+ - README
50
+ - lib/helpful_utils.rb
51
+ - lib/helpful_utils/activerecord_ext/humanized_attributes.rb
52
+ - lib/helpful_utils/common/configuration.rb
53
+ - lib/helpful_utils/core_ext/array.rb
54
+ - lib/helpful_utils/core_ext/hash.rb
55
+ - lib/helpful_utils/core_ext/kernel.rb
56
+ - lib/helpful_utils/core_ext/string.rb
57
+ - lib/helpful_utils/patching_utils/event_machine.rb
58
+ - lib/helpful_utils/patching_utils/inheritance_tree.rb
59
+ - test/core_tests.rb
60
+ has_rdoc: true
61
+ homepage: http://github.com/strikeroff/helpful_utils
62
+ post_install_message:
63
+ rdoc_options:
64
+ - --line-numbers
65
+ - --inline-source
66
+ - --title
67
+ - Helpful_utils
68
+ - --main
69
+ - README
70
+ - -c utf-8
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: "0"
78
+ version:
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: "1.2"
84
+ version:
85
+ requirements: []
86
+
87
+ rubyforge_project: helpful_utils
88
+ rubygems_version: 1.2.0
89
+ signing_key:
90
+ specification_version: 2
91
+ summary: collection of helpful utils,hacks , etc
92
+ test_files: []
93
+