Skip to content

Commit

Permalink
some fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
strikeroff committed Sep 10, 2009
1 parent 8cf3b1d commit 3cb69d2
Show file tree
Hide file tree
Showing 15 changed files with 309 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
@@ -0,0 +1,3 @@
.idea
.svn
pkg
1 change: 1 addition & 0 deletions CHANGELOG
@@ -0,0 +1 @@
v0.0.1 "Add String extensions, event machine, deep clone for Hash and Array, humanized attributes and project configuration support"
15 changes: 15 additions & 0 deletions Manifest
@@ -0,0 +1,15 @@
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
2 changes: 2 additions & 0 deletions README
@@ -0,0 +1,2 @@
= Russian =
Примеры использования либы можно посмотреть в директории 'examples'
22 changes: 22 additions & 0 deletions Rakefile
@@ -0,0 +1,22 @@
require "echoe"

Echoe.new( "helpful_utils" ) do |p|
p.author = [ "Ilya Vesov","Anatoly Lapshin"]
p.summary = "collection of helpful utils,hacks , etc"
p.email = "strikeroff@gmail.com"
p.url = "http://github.com/strikeroff/helpful_utils"

p.runtime_dependencies = ['activesupport']
p.development_dependencies = []

p.need_tar_gz = false
p.retain_gemspec = true
p.gemspec_name = 'heplful_utils.gemspec'
p.test_pattern = ["test/**/*_test.rb"]

p.clean_pattern.push 'lib/*-*'
p.has_rdoc = true
p.rdoc_pattern = ["README", "CHANGELOG", "lib/**/*.rb"]
p.rdoc_options << "-c utf-8"
p.ignore_pattern = [".gitignore", "doc", "examples", ".idea", "coverage.data", "*.bat"]
end
7 changes: 7 additions & 0 deletions gem-build.bat
@@ -0,0 +1,7 @@
call gem uninstall helpful_utils
del /Q pkg
call rake manifest
call rake install
cd pkg
call gem install helpful_utils-0.0.1
cd ..
3 changes: 3 additions & 0 deletions gem-build.sh
@@ -0,0 +1,3 @@
#!/bin/bash
rm pkg/*.gem
rake manifest && rake gem && gem install -l pkg/*.gem
34 changes: 34 additions & 0 deletions heplful_utils.gemspec
@@ -0,0 +1,34 @@
# -*- encoding: utf-8 -*-

Gem::Specification.new do |s|
s.name = %q{helpful_utils}
s.version = "0.0.1"

s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Ilya Vesov, Anatoly Lapshin"]
s.date = %q{2009-09-10}
s.description = %q{collection of helpful utils,hacks , etc}
s.email = %q{strikeroff@gmail.com}
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"]
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"]
s.has_rdoc = true
s.homepage = %q{http://github.com/strikeroff/helpful_utils}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Helpful_utils", "--main", "README", "-c utf-8"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{helpful_utils}
s.rubygems_version = %q{1.3.1}
s.summary = %q{collection of helpful utils,hacks , etc}

if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2

if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>, [">= 0"])
else
s.add_dependency(%q<activesupport>, [">= 0"])
end
else
s.add_dependency(%q<activesupport>, [">= 0"])
end
end
26 changes: 26 additions & 0 deletions lib/helpful_utils.rb
@@ -0,0 +1,26 @@
require File.join(File.dirname(__FILE__), "helpful_utils", "common", "configuration")


Dir[File.join(File.dirname(__FILE__), "helpful_utils", "patching_utils")<<"/*.rb"].each do |file|
require file
end

# Some files need to be required after iitialize
Rails::Initializer.class_eval do
def after_initialize_with_helpful_utils
HelpfulUtils::EventMachine.after_initialize_with_helpful_utils
after_initialize_without_helpful_utils
end
alias_method_chain :after_initialize, :helpful_utils
end

HelpfulUtils::EventMachine.subscribe :after_initialize_with_helpful_utils do

Dir[File.join(File.dirname(__FILE__), "helpful_utils", "core_ext")<<"/*.rb"].each do |file|
require file
end

require File.join(File.dirname(__FILE__), "helpful_utils", "activerecord_ext", "humanized_attributes.rb")


end
10 changes: 10 additions & 0 deletions lib/helpful_utils/activerecord_ext/humanized_attributes.rb
@@ -0,0 +1,10 @@
class ActiveRecord::Base
def self.human_attribute_name(attribute_key_name)
default = attribute_key_name.humanize
if self.const_defined?('HUMANIZED_ATTRIBUTES')
self.const_get('HUMANIZED_ATTRIBUTES')[attribute_key_name.to_sym] || default
else
default
end
end
end
50 changes: 50 additions & 0 deletions lib/helpful_utils/common/configuration.rb
@@ -0,0 +1,50 @@
class Configuration
# Загрузка конфигурационных файлов в окружение Configuration из папки RAILS_ROOT/config/project(по умолчанию).
# Для каждого найденного yaml файла в папке project мы производим загрузку в окружение.
# Все это делается в целях удобства обращения к конфигурации.
# Доступ к конфигам из проекта - Configuration.НАЗВАНИЕ_ФАЙЛА.КЛЮЧ

cattr_accessor :path_to_config_dir
@@path_to_config_dir = "#{::RAILS_ROOT}/config/project"

def self.load_configurations
if defined? ::RAILS_ROOT
Dir["#{path_to_config_dir}/*.yaml"].each do |config_file|
load_configuration_from_file(config_file)
end
end

end

def self.has?(config_name)
self.method_defined? config_name
end


def self.load_configuration_from_file ( config_file )
config = YAML.load_file( config_file )
if config.instance_of? Hash
attrs = []
config.each_key { |key| attrs << key.to_sym } # извлекаем имена полей
config_struct = Struct.new *attrs # создаем структуру с этими полями
new_config = config_struct.new # создаем объект этой структуры
config_struct.members.each do |attr_name| # инициализируем значения полей объекта
new_config.send( "#{attr_name}=", config[attr_name] )
end
config = new_config # отображаем трансформацию в конфиг
end
attr_name = File.basename( config_file, ".yaml" )

self.class_eval do
cattr_accessor attr_name.to_sym # создаем в модуле аттрибут
end

self.send("#{attr_name}=", config)
end


end


Configuration.load_configurations

27 changes: 27 additions & 0 deletions lib/helpful_utils/core_ext/kernel.rb
@@ -0,0 +1,27 @@
module Kernel # :nodoc:
# Переключение области видимости на объект.
# Использовать осторожно. Рекоммендуется применять, когда в коде идет несколько операций
# над одним объектом. Таким образом следующий код:
#
# Gionet.contexts.set_context(:region, :volga)
# Gionet.contexts.set_context(:site, "gionet.ru")
# Gionet.contexts.set_context(:special, special_object)
# p Gionet.contexts.slice
# Gionet.contexts.run
#
# можно преобразовать в следующий:
#
# with Gionet.contexts do
# set_context(:region, :volga)
# set_context(:site, "gionet.ru")
# set_context(:special, special_object)
# p slice
# run
# end
#
# Внимание при использовании необходимо по причине того, что внутри блока происходит
# смешивание областей видимости самого объекта и окружения из которого он вызывается.
def with(object, &block)
object.instance_eval &block
end
end
57 changes: 57 additions & 0 deletions lib/helpful_utils/core_ext/string.rb
@@ -0,0 +1,57 @@
module HelpfulUtils
module CoreExt
module String

module JSON
# Если вызывать у строки с русским текстом стандартный метод to_json, а потом попробовать отобразить ее
# то получится что то невразумительное.Данный метод исправляет проблему. Пример
# "тут русский текст".to_json(:russian=>true)
# по умолчанию russian == false
def to_json_with_russian_support(options = nil) #:nodoc:
result = nil
unless options.blank?
if options[:russian]== true
json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
}
json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
result = json + '"'
end
end
if result.blank?
result = to_json_without_russian_support options
end
result
end

alias_method_chain :to_json, :russian_support


# Проверка,является ли строка JSON'ом
def json?
return true if !self.blank? && ActiveSupport::JSON.decode(self).is_a?(Hash)
rescue ActiveSupport::JSON::ParseError
false
end
end
module UrlHelpers
# can raise URI::InvalidURIError
# приводит строку к полноценному URL
def to_url(prefix="http://")
return nil if self.blank?
if URI.parse(self).class != URI::HTTP
"#{prefix}#{self.strip}"
else
self.dup
end
end
end
end
end
end


class String
include HelpfulUtils::CoreExt::String::JSON
include HelpfulUtils::CoreExt::String::UrlHelpers
end
38 changes: 38 additions & 0 deletions lib/helpful_utils/patching_utils/event_machine.rb
@@ -0,0 +1,38 @@
module HelpfulUtils
# Класс служит для подписывания на события и выполнения кода по выполнении этих событий.
# Пример с подписыванием на событие after_initialize htkmcjd
# Rails::Initializer.class_eval do
# def after_initialize_with_helpful_utils
# HelpfulUtils::EventMachine.after_initialize_with_helpful_utils
# after_initialize_without_helpful_utils
# end
#
# alias_method_chain :after_initialize, :helpful_utils
# end
#
# HelpfulUtils::EventMachine.subscribe :after_initialize_with_helpful_utils do
# require File.join(File.dirname(__FILE__), "helpful_utils", "activerecord_ext", "humanized_attributes.rb")
# end
# Feel free in use this tool,it's powerfull =)



class EventMachine
@@actions_and_blocks = {}
# cattr_accessor :actions_and_blocks
class << self
def method_missing(method_symbol, *parameters)#:nodoc:
if @@actions_and_blocks.has_key? method_symbol
@@actions_and_blocks[method_symbol].each do |action|
action.call *parameters
end
end
end

def subscribe(event_symbol, &block)
@@actions_and_blocks[event_symbol] ||= []
@@actions_and_blocks[event_symbol] << block
end
end
end
end
14 changes: 14 additions & 0 deletions lib/helpful_utils/patching_utils/inheritance_tree.rb
@@ -0,0 +1,14 @@
module HelpfulUtils
module InheritanceTree
def objects
class_objects = []
ObjectSpace.each_object(self) {|e| class_objects << e }
class_objects
end

def class_children
(@class_objects ||= Class.objects).select {|e| e.superclass == self }
end
end
end
Module.send :include, HelpfulUtils::InheritanceTree

0 comments on commit 3cb69d2

Please sign in to comment.