total_compressor 0.0.1 → 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore CHANGED
@@ -2,12 +2,8 @@
2
2
  *.rbc
3
3
  .bundle
4
4
  .config
5
- .yardoc
6
- Gemfile.lock
7
- InstalledFiles
8
- _yardoc
9
5
  coverage
10
- doc/
6
+ InstalledFiles
11
7
  lib/bundler/man
12
8
  pkg
13
9
  rdoc
@@ -15,3 +11,8 @@ spec/reports
15
11
  test/tmp
16
12
  test/version_tmp
17
13
  tmp
14
+
15
+ # YARD artifacts
16
+ .yardoc
17
+ _yardoc
18
+ doc/
data/Gemfile.lock ADDED
@@ -0,0 +1,33 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ total_compressor (0.1.2)
5
+ awesome_print
6
+ rubyzip (~> 0.9.9)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ awesome_print (1.1.0)
12
+ diff-lcs (1.2.5)
13
+ rake (10.1.0)
14
+ rspec (2.14.1)
15
+ rspec-core (~> 2.14.0)
16
+ rspec-expectations (~> 2.14.0)
17
+ rspec-mocks (~> 2.14.0)
18
+ rspec-core (2.14.7)
19
+ rspec-expectations (2.14.4)
20
+ diff-lcs (>= 1.1.3, < 2.0)
21
+ rspec-mocks (2.14.4)
22
+ rubyzip (0.9.9)
23
+
24
+ PLATFORMS
25
+ ruby
26
+
27
+ DEPENDENCIES
28
+ awesome_print
29
+ bundler (~> 1.3)
30
+ rake
31
+ rspec (>= 2.14)
32
+ rubyzip (~> 0.9.9)
33
+ total_compressor!
data/LICENSE.txt CHANGED
@@ -1,7 +1,5 @@
1
1
  Copyright (c) 2013 PhlowerTeam
2
2
 
3
- https://github.com/phlowerteam
4
-
5
3
  MIT License
6
4
 
7
5
  Permission is hereby granted, free of charge, to any person obtaining
data/README.md CHANGED
@@ -1,4 +1,5 @@
1
- # TotalCompressor
1
+ total_compressor
2
+ ================
2
3
 
3
4
  Tool (wrapper) for compression and handling multiple type of archives.
4
5
 
@@ -28,14 +29,18 @@ Or install it yourself as:
28
29
 
29
30
  ## Usage
30
31
 
31
- Command line: tcomp [<key>] path
32
- <key> - determine supported type of compression:
33
- z - use Zip
34
- g - use GZip
35
- r - use RAR
36
- 7 - use 7z
32
+ Command line:
33
+
34
+ tcomp [<key>] path
35
+
36
+ <key> - determines supported type of compression:
37
+ z - use Zip
38
+ g - use GZip (can't compress folder, only file)
39
+ r - use RAR
40
+ 7 - use 7z
37
41
 
38
42
  Examples:
43
+
39
44
  tcomp z '/home/alex/The Lord of the Rings.txt' # creates '/home/alex/The Lord of the Rings.txt.zip'
40
45
  tcomp /home/alex/Hobbit.txt.7z # creates /home/alex/Hobbit.txt
41
46
 
@@ -87,4 +92,4 @@ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
87
92
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
88
93
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
89
94
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
90
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
95
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -52,11 +52,11 @@ module TotalCompressor
52
52
 
53
53
  def show_help
54
54
  puts %Q{
55
- Total Compressor, v0.1, 2013, MIT License, https://github.com/phlowerteam
55
+ Total Compressor, v0.1.2, 2013, MIT License, https://github.com/phlowerteam
56
56
  Tool (wrapper) for compression and handling multiple type of archives.
57
57
 
58
58
  Usage: tcomp [<key>] path
59
- <key> - determine supported type of compression:
59
+ <key> - determines supported type of compression:
60
60
  z - use Zip
61
61
  g - use GZip (can't compress folder, only file)
62
62
  r - use RAR
@@ -70,8 +70,8 @@ module TotalCompressor
70
70
  end
71
71
  end
72
72
 
73
- load 'lib/total_compressor/compressors/base_compressor.rb'
74
- load 'lib/total_compressor/compressors/t_zip.rb'
75
- load 'lib/total_compressor/compressors/t_gzip.rb'
76
- load 'lib/total_compressor/compressors/t_rar.rb'
77
- load 'lib/total_compressor/compressors/t_7z.rb'
73
+ require 'total_compressor/compressors/base_compressor'
74
+ require 'total_compressor/compressors/t_zip'
75
+ require 'total_compressor/compressors/t_gzip'
76
+ require 'total_compressor/compressors/t_rar'
77
+ require 'total_compressor/compressors/t_7z'
@@ -0,0 +1,187 @@
1
+ module TotalCompressor
2
+ class BaseCompressor
3
+ PROJECT = Dir.pwd
4
+ TEXT_FILE = 'test/text_file.txt'
5
+ FILE = "#{PROJECT}/#{TEXT_FILE}"
6
+
7
+ HOME = Dir.home
8
+ TEST = "tmp_#{Time.now.to_i}"
9
+
10
+ TEST_FILE = "#{HOME}/#{TEST}/#{TEXT_FILE.split('/').last}"
11
+ TEMP_FOLDER = "#{HOME}/#{TEST}/"
12
+ TEST_FOLDER = "#{HOME}/#{TEST}/#{TEST}"
13
+ TEST_FOLDER_UNCOMPRESSED = "#{HOME}/#{TEST}/UNCOMPRESSED"
14
+
15
+ HASH_TYPE = {
16
+ 'z' => 'zip',
17
+ 'r' => 'rar',
18
+ '7' => '7z',
19
+ 'g' => 'gzip'
20
+ }
21
+
22
+ TYPE = {
23
+ 'zip' => {
24
+ 'tool' => 'zip',
25
+ 'compress_file' => '-9',
26
+ 'compress_folder' => '-9r',
27
+ 'success_message' => 'deflated'
28
+ },
29
+ 'rar' => {
30
+ 'tool' => 'rar',
31
+ 'compress_file' => 'a',
32
+ 'compress_folder' => 'a',
33
+ 'decompress' => 'x',
34
+ 'success_message' => 'Done'
35
+ },
36
+ '7z' => {
37
+ 'tool' => '7z',
38
+ 'compress_file' => 'a',
39
+ 'compress_folder' => 'a',
40
+ 'decompress' => 'x',
41
+ 'success_message' => 'Everything is Ok'
42
+ },
43
+ 'gzip' => {}
44
+ }
45
+
46
+ MSG = {
47
+ :unsupported => 'Unsupported archive type!',
48
+ :exception => 'Exception!',
49
+ :incorrect => 'Incorrect archive filename!'
50
+ }
51
+
52
+ def save_current_dir
53
+ @current_dir = Dir.pwd
54
+ end
55
+
56
+ def back_to_last_dir
57
+ chdir(@current_dir)
58
+ end
59
+
60
+ def get_folder(path)
61
+ path.split('/')[0..-2].join('/')
62
+ end
63
+
64
+ def chdir(folder)
65
+ if File.directory?(folder)
66
+ Dir.chdir(folder)
67
+ true
68
+ else
69
+ false
70
+ end
71
+ end
72
+
73
+ def get_file(path)
74
+ file = path.split('/')[-1]
75
+ file ? file : path
76
+ end
77
+
78
+ def prepare_test_files
79
+ FileUtils.rm_rf(TEMP_FOLDER, secure: true)
80
+ Dir.mkdir(TEMP_FOLDER)
81
+ Dir.mkdir(TEST_FOLDER)
82
+ Dir.mkdir(TEST_FOLDER_UNCOMPRESSED)
83
+ FileUtils.cp("#{FILE}", TEMP_FOLDER)
84
+ FileUtils.cp("#{FILE}", TEST_FOLDER)
85
+ chdir(HOME)
86
+ end
87
+
88
+ def utilize_test_files
89
+ FileUtils.rm_rf("#{TEMP_FOLDER}", secure: true)
90
+ chdir(PROJECT)
91
+ end
92
+
93
+ def test(format)
94
+ test_sets = [
95
+ TotalCompressor::BaseCompressor::TEST_FILE,
96
+ TotalCompressor::BaseCompressor::TEST_FOLDER
97
+ ]
98
+ result = {
99
+ :success => true
100
+ }
101
+ prepare_test_files
102
+ test_sets.each do |test_set|
103
+ next if skip_test?(format, test_set)
104
+ res = eval("TotalCompressor::T#{format.capitalize}.new.compress(\'#{test_set}\')")
105
+ if res[:success]
106
+ FileUtils.cp("#{res[:file]}", TEST_FOLDER_UNCOMPRESSED)
107
+ res = eval("TotalCompressor::T#{format.capitalize}.new.decompress(\'#{TEST_FOLDER_UNCOMPRESSED}/#{res[:file].split('/').last}\')")
108
+ result[:success] = false unless res[:success]
109
+ else
110
+ result[:success] = false
111
+ end
112
+ end
113
+ utilize_test_files
114
+ result[:success] ? 'Success' : 'Failure'
115
+ end
116
+
117
+ def skip_test?(format, test_set)
118
+ true if File.directory?(test_set) && format == 'gzip'
119
+ end
120
+
121
+ def compress(path, format)
122
+ save_current_dir
123
+ result = {
124
+ :success => false
125
+ }
126
+ folder = get_folder(path)
127
+ return result unless chdir(folder)
128
+ begin
129
+ file = get_file(path)
130
+ archive = file + ".#{format}"
131
+ if file
132
+ message = if File.directory?(path)
133
+ %x[#{TYPE[format]['tool']} #{TYPE[format]['compress_folder']} #{archive} #{file}]
134
+ else
135
+ %x[#{TYPE[format]['tool']} #{TYPE[format]['compress_file']} #{archive} #{file}]
136
+ end
137
+ if message && message.match(/#{TYPE[format]['success_message']}/)
138
+ result[:success] = true
139
+ result[:file] = "#{folder}/#{archive}"
140
+ else
141
+ result[:error] = message
142
+ end
143
+ else
144
+ result[:error] = BaseCompressor::MSG[:incorrect]
145
+ end
146
+ rescue
147
+ result[:error] = BaseCompressor::MSG[:exception]
148
+ ensure
149
+ back_to_last_dir
150
+ end
151
+ return_result(result)
152
+ end
153
+
154
+ def decompress(path, format)
155
+ save_current_dir
156
+ result = {
157
+ :success => false,
158
+ :files => []
159
+ }
160
+ folder = get_folder(path)
161
+ Dir.chdir(folder)
162
+ begin
163
+ file = get_file(path)
164
+ previous_entries = Dir.entries(Dir.pwd)
165
+ %x[#{TYPE[format]['tool']} #{TYPE[format]['decompress']} #{file}]
166
+ new_entries = Dir.entries(Dir.pwd)
167
+ uncompressed_entries = new_entries - previous_entries
168
+ uncompressed_entries.each{|entry| result[:files] << "#{folder}/#{entry}" }
169
+ result[:success] = true
170
+ rescue
171
+ result[:error] = BaseCompressor::MSG[:exception]
172
+ ensure
173
+ back_to_last_dir
174
+ end
175
+ return_result(result)
176
+ end
177
+
178
+ def get_format
179
+ self.class.to_s.split('::').last.downcase[1..-1]
180
+ end
181
+
182
+ def return_result(result)
183
+ ap result unless result[:success]
184
+ result
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,15 @@
1
+ module TotalCompressor
2
+ class T7z < BaseCompressor
3
+ def test
4
+ super(get_format)
5
+ end
6
+
7
+ def compress(path)
8
+ super(path, get_format)
9
+ end
10
+
11
+ def decompress(path)
12
+ super(path, get_format)
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,56 @@
1
+ module TotalCompressor
2
+ class TGzip < BaseCompressor
3
+ def test
4
+ super(get_format)
5
+ end
6
+
7
+ def compress(path)
8
+ save_current_dir
9
+ result = {
10
+ :success => false
11
+ }
12
+ raise if File.directory?(path)
13
+ folder = get_folder(path)
14
+ return result unless chdir(folder)
15
+ begin
16
+ file = get_file(path)
17
+ archive = file + ".#{get_format}"
18
+ Zlib::GzipWriter.open("#{path}.gzip") do |gz|
19
+ gz.write(IO.read(path))
20
+ result = {
21
+ :success => true,
22
+ :file => "#{folder}/#{archive}"
23
+ }
24
+ end
25
+ rescue
26
+ result[:error] = 'exception'
27
+ ensure
28
+ back_to_last_dir
29
+ end
30
+ return_result(result)
31
+ end
32
+
33
+ def decompress(path)
34
+ save_current_dir
35
+ result = {
36
+ :success => false,
37
+ :files => []
38
+ }
39
+ begin
40
+ Zlib::GzipReader.open(path) do |gz|
41
+ file = path.split('.')[0..-2].join('.')
42
+ IO.write(file, gz.read)
43
+ result = {
44
+ :success => true,
45
+ :file => file
46
+ }
47
+ end
48
+ rescue
49
+ result[:error] = 'exception'
50
+ ensure
51
+ back_to_last_dir
52
+ end
53
+ return_result(result)
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,15 @@
1
+ module TotalCompressor
2
+ class TRar < BaseCompressor
3
+ def test
4
+ super(get_format)
5
+ end
6
+
7
+ def compress(path)
8
+ super(path, get_format)
9
+ end
10
+
11
+ def decompress(path)
12
+ super(path, get_format)
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,35 @@
1
+ module TotalCompressor
2
+ class TZip < BaseCompressor
3
+ def test
4
+ super(get_format)
5
+ end
6
+
7
+ def compress(path)
8
+ super(path, get_format)
9
+ end
10
+
11
+ def decompress(path)
12
+ save_current_dir
13
+ result = {
14
+ :success => false,
15
+ :files => []
16
+ }
17
+ begin
18
+ folder = get_folder(path)
19
+ Zip::ZipFile.open(path) do |zip_file|
20
+ dir = zip_file
21
+ dir.entries.each do |file|
22
+ zip_file.extract(file, "#{folder}/#{file}")
23
+ result[:files] << "#{folder}/#{file}"
24
+ end
25
+ end
26
+ result[:success] = true
27
+ rescue
28
+ result[:error] = 'exception'
29
+ ensure
30
+ back_to_last_dir
31
+ end
32
+ return_result(result)
33
+ end
34
+ end
35
+ end
@@ -1,3 +1,3 @@
1
1
  module TotalCompressor
2
- VERSION = "0.0.1"
2
+ VERSION = "0.1.2"
3
3
  end
@@ -0,0 +1,409 @@
1
+ Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.
2
+ Ruby embodies syntax inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp.[9] It supports multiple programming paradigms, including functional, object oriented, and imperative. It also has a dynamic type system and automatic memory management. Therefore, it is similar in varying degrees to Smalltalk, Python, Perl, Lisp, Dylan, and CLU.
3
+ The standard and already retired[10] 1.8.7 implementation was written in C, as a single-pass interpreted language. Starting with the 1.9 branch, and continuing with the current 2.0 branch, YARV has been used, and will eventually supersede the slower Ruby MRI. The language specifications for Ruby were developed by the Open Standards Promotion Center of the Information-Technology Promotion Agency (a Japanese government agency) for submission to the Japanese Industrial Standards Committee and then to the International Organization for Standardization. It was accepted as a Japanese Industrial Standard (JIS X 3017) in 2011[11] and an international standard (ISO/IEC 30170) in 2012.[12] As of 2010, there are a number of complete or upcoming alternative implementations of Ruby, including YARV, JRuby, Rubinius, IronRuby, MacRuby (and its iOS counterpart, RubyMotion), mruby, HotRuby, Topaz and Opal. Each takes a different approach, with IronRuby, JRuby, MacRuby and Rubinius providing just-in-time compilation and MacRuby and mruby also providing ahead-of-time compilation.
4
+
5
+ History[edit]
6
+
7
+ Ruby was conceived on February 24, 1993 by Yukihiro Matsumoto who wished to create a new language that balanced functional programming with imperative programming.[13] Matsumoto has said, "I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language."[14]
8
+ At a Google Tech Talk in 2008 Matsumoto further stated, "I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language."[15]
9
+ Choice of the name "Ruby"[edit]
10
+ The name "Ruby" originated during an online chat session between Matsumoto and Keiju Ishitsuka on February 24, 1993, before any code had been written for the language.[16] Initially two names were proposed: "Coral" and "Ruby". Matsumoto chose the latter in a later e-mail to Ishitsuka.[17] Matsumoto later noted a factor in choosing the name "Ruby" – it was the birthstone of one of his colleagues.[18][19]
11
+ First publication[edit]
12
+ The first public release of Ruby 0.95 was announced on Japanese domestic newsgroups on December 21, 1995.[20][21] Subsequently three more versions of Ruby were released in two days.[16] The release coincided with the launch of the Japanese-language ruby-list mailing list, which was the first mailing list for the new language.
13
+ Already present at this stage of development were many of the features familiar in later releases of Ruby, including object-oriented design, classes with inheritance, mixins, iterators, closures, exception handling and garbage collection.[22]
14
+ Ruby 1.0[edit]
15
+ Ruby reached version 1.0 on December 25, 1996.[16]
16
+ Following the release of Ruby 1.3 in 1999 the first English language mailing list ruby-talk began,[14] which signalled a growing interest in the language outside of Japan. In September 2000, the first English language book Programming Ruby was printed, which was later freely released to the public, further widening the adoption of Ruby amongst English speakers.
17
+ [icon] This section requires expansion with: history and new features for pre-1.9 versions. (May 2012)
18
+ Ruby 1.2[edit]
19
+ Ruby 1.2 was initially released in December 1998.
20
+ Ruby 1.4[edit]
21
+ Ruby 1.4 was initially released in August 1999.
22
+ Ruby 1.6[edit]
23
+ Ruby 1.6 was initially released in September 2000.
24
+ Ruby 1.8[edit]
25
+ Ruby 1.8 was initially released in August 2003, was stable for a long time, and was retired June 2013.[10] Although deprecated, there is still code based on it. Ruby 1.8 is incompatible with Ruby 1.9.
26
+ Ruby on Rails[edit]
27
+ Around 2005, interest in the Ruby language surged in tandem with Ruby on Rails, a popular web application framework written in Ruby. Rails is frequently credited with making Ruby "famous".[23]
28
+ Ruby 1.9[edit]
29
+ Ruby 1.9 was released in December 2007. Effective with Ruby 1.9.3, released October 31, 2011,[24] Ruby switched from being dual-licensed under the Ruby License and the GPL to being dual-licensed under the Ruby License and the two-clause BSD license.[25] Adoption of 1.9 was slowed by changes from 1.8 which required many popular third party gems to be rewritten.
30
+ Ruby 1.9 introduces many significant changes over the 1.8 series.[26] Examples:
31
+ block local variables (variables that are local to the block in which they are declared)
32
+ an additional lambda syntax: f = ->(a,b) { puts a + b }
33
+ per-string character encodings are supported
34
+ new socket API (IPv6 support)
35
+ require_relative import security
36
+ Ruby 2.0[edit]
37
+ Ruby 2.0 added several new features, including:
38
+ method keyword arguments,
39
+ a new method, Module#prepend, for extending a class,
40
+ a new literal for creating an array of symbols,
41
+ new API for the lazy evaluation of Enumerables, and
42
+ a new convention of using #to_h to convert objects to Hashes.[27]
43
+ Ruby 2.0 is intended to be fully backward compatible with Ruby 1.9.3. As of the official 2.0.0 release on February 24, 2013, there were only five known (minor) incompatibilities.[28]
44
+ Philosophy[edit]
45
+
46
+ Matsumoto has said that Ruby is designed for programmer productivity and fun, following the principles of good user interface design.[29] He stresses that systems design needs to emphasize human, rather than computer, needs:[30]
47
+ Often people, especially computer engineers, focus on the machines. They think, "By doing this, the machine will run faster. By doing this, the machine will run more effectively. By doing this, the machine will something something something." They are focusing on machines. But in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves.
48
+ Ruby is said to follow the principle of least astonishment (POLA), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said that he had not applied the principle of least surprise to the design of Ruby,[30] but nevertheless the phrase has come to be closely associated with the Ruby programming language. The phrase has itself been a source of surprise, as novice users may take it to mean that Ruby's behaviors try to closely match behaviors familiar from other languages. In a May 2005 discussion on the newsgroup comp.lang.ruby, Matsumoto attempted to distance Ruby from POLA, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. If that personal standard remains consistent, there would be few surprises for those familiar with the standard.[31]
49
+ Matsumoto defined it this way in an interview:[30]
50
+ Everyone has an individual background. Someone may come from Python, someone else may come from Perl, and they may be surprised by different aspects of the language. Then they come up to me and say, 'I was surprised by this feature of the language, so Ruby violates the principle of least surprise.' Wait. Wait. The principle of least surprise is not for you only. The principle of least surprise means principle of least my surprise. And it means the principle of least surprise after you learn Ruby very well. For example, I was a C++ programmer before I started designing Ruby. I programmed in C++ exclusively for two or three years. And after two years of C++ programming, it still surprises me.
51
+ Features[edit]
52
+
53
+ Thoroughly object-oriented with inheritance, mixins and metaclasses[32]
54
+ Dynamic typing and duck typing
55
+ Everything is an expression (even statements) and everything is executed imperatively (even declarations)
56
+ Succinct and flexible syntax[33] that minimizes syntactic noise and serves as a foundation for domain-specific languages[34]
57
+ Dynamic reflection and alteration of objects to facilitate metaprogramming[35]
58
+ Lexical closures, iterators and generators, with a unique block syntax[36]
59
+ Literal notation for arrays, hashes, regular expressions and symbols
60
+ Embedding code in strings (interpolation)
61
+ Default arguments
62
+ Four levels of variable scope (global, class, instance, and local) denoted by sigils or the lack thereof
63
+ Garbage collection
64
+ First-class continuations
65
+ Strict boolean coercion rules (everything is true except false and nil)
66
+ Exception handling
67
+ Operator overloading
68
+ Built-in support for rational numbers, complex numbers and arbitrary-precision arithmetic
69
+ Custom dispatch behavior (through method_missing and const_missing)
70
+ Native threads and cooperative fibers (fibers are 1.9/YARV feature)
71
+ Initial support for Unicode and multiple character encodings (no ICU support)[37]
72
+ Native plug-in API in C
73
+ Interactive Ruby Shell (a REPL)
74
+ Centralized package management through RubyGems
75
+ Implemented on all major platforms
76
+ Large standard library, including modules for YAML, JSON, XML, CGI, OpenSSL, HTTP, FTP, RSS, curses, zlib, and Tk[38]
77
+ Semantics[edit]
78
+
79
+ Ruby is object-oriented: every value is an object, including classes and instances of types that many other languages designate as primitives (such as integers, booleans, and "null"). Variables always hold references to objects. Every function is a method and methods are always called on an object. Methods defined at the top level scope become members of the Object class. Since this class is an ancestor of every other class, such methods can be called on any object. They are also visible in all scopes, effectively serving as "global" procedures. Ruby supports inheritance with dynamic dispatch, mixins and singleton methods (belonging to, and defined for, a single instance rather than being defined on the class). Though Ruby does not support multiple inheritance, classes can import modules as mixins.
80
+ Ruby has been described as a multi-paradigm programming language: it allows procedural programming (defining functions/variables outside classes makes them part of the root, 'self' Object), with object orientation (everything is an object) or functional programming (it has anonymous functions, closures, and continuations; statements all have values, and functions return the last evaluation). It has support for introspection, reflection and metaprogramming, as well as support for interpreter-based[39] threads. Ruby features dynamic typing, and supports parametric polymorphism.
81
+ According to the Ruby FAQ,[40] "If you like Perl, you will like Ruby and be right at home with its syntax. If you like Smalltalk, you will like Ruby and be right at home with its semantics. If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."
82
+ Syntax[edit]
83
+
84
+ The syntax of Ruby is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords. In contrast to Perl, variables are not obligatorily prefixed with a sigil. When used, the sigil changes the semantics of scope of the variable. One difference from C and Perl is that keywords are typically used to define logical code blocks, without braces (i.e., pair of { and }). For practical purposes there is no distinction between expressions and statements.[41] Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.
85
+ One of the differences of Ruby compared to Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc.). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby can be created with a single line of code via metaprogramming; however, accessor methods can also be created in the traditional fashion of C++ and Java. As invocation of these methods does not require the use of parentheses, it is trivial to change an instance variable into a full function, without modifying a single line of code or having to do any refactoring achieving similar functionality to C# and VB.NET property members.
86
+ Python's property descriptors are similar, but come with a tradeoff in the development process. If one begins in Python by using a publicly exposed instance variable, and later changes the implementation to use a private instance variable exposed through a property descriptor, code internal to the class may need to be adjusted to use the private variable rather than the public property. Ruby’s design forces all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby, one never directly accesses the internal members of a class from outside of it; rather, one passes a message to the class and receives a response.
87
+ See the Examples section below for samples of code demonstrating Ruby syntax.
88
+ Deviations from behavior elsewhere[edit]
89
+
90
+ Some features which differ notably from languages such as C or Perl:
91
+ The language syntax is sensitive to the capitalization of identifiers, in all cases treating capitalized variables as constants. Class and module names are constants and refer to objects derived from Class and Module.
92
+ The sigils $ and @ do not indicate variable data type as in Perl, but rather function as scope resolution operators.
93
+ Floating point literals must have digits both side of the decimal point: neither .5 nor 2. are valid floating point literals, but 0.5 and 2.0 are.
94
+ (In Ruby, integer literals are objects that can have methods apply to them, so requiring a digit after a decimal point helps to clarify whether 1.e5 should be parsed analogously to 1.to_f or as the exponential-format floating literal 1.0e5. The reason for requiring a digit before the decimal point is less clear; it might relate either to method invocation again, or perhaps to the .. and ... operators, for example in the fragment 0.1...3.)
95
+ Boolean non-boolean datatypes are permitted in boolean contexts (unlike in e.g. Smalltalk and Java), but their mapping to boolean values differs markedly from some other languages: 0 and "empty" (e.g. empty list, string or associative array) all evaluate to true, thus changing the meaning of some common idioms in related or similar languages such as Lisp, Perl and Python.
96
+ A consequence of this rule is that Ruby methods by convention — for example, regular-expression searches — return numbers, strings, lists, or other non-false values on success, but nil on failure.
97
+ Versions prior to 1.9 use plain integers to represent single characters, much like C. This may cause surprises when slicing strings: "abc"[0] yields 97 (the ASCII code of the first character in the string); to obtain "a" use "abc"[0,1] (a substring of length 1) or "abc"[0].chr.
98
+ The notation statement until expression does not run the statement if the expression is already true. (The behavior is like Perl, but unlike other languages' equivalent statements, e.g. do { statement } while (!(expression)); in C/C++/...). This is because statement until expression is actually syntactic sugar over until expression; statement; end, the equivalent of which in C/C++ is while (!(expression)) { statement; }, just as statement if expression is equivalent to if (expression) { statement; }. However, the notation begin statement end until expression in Ruby will in fact run the statement once even if the expression is already true, acting similar to the do-while of other languages. (Matsumoto has expressed a desire to remove the special behavior of begin statement end until expression,[42] but it still exists as of Ruby 2.0.)
99
+ Because constants are references to objects, changing what a constant refers to generates a warning, but modifying the object itself does not. For example, Greeting << " world!" if Greeting == "Hello" does not generate an error or warning. This is similar to final variables in Java or a const pointer to a non-const object in C++, but Ruby provides the functionality to "freeze" an object, unlike Java.
100
+ Some features which differ notably from other languages:
101
+ The usual operators for conditional expressions, and and or, do not follow the normal rules of precedence: and does not bind tighter than or. Ruby also has expression operators || and && that work as expected.
102
+ A list of so-called gotchas may be found in Hal Fulton's book The Ruby Way, 2nd ed (ISBN 0-672-32884-4), Section 1.5. A similar list in the 1st edition pertained to an older version of Ruby (version 1.6), some problems of which have been fixed in the meantime. For example, retry now works with while, until, and for, as well as with iterators.
103
+ Interaction[edit]
104
+
105
+ See also: Interactive Ruby Shell
106
+ The Ruby official distribution also includes irb, an interactive command-line interpreter which can be used to test code quickly. The following code fragment represents a sample session using irb:
107
+ $ irb
108
+ irb(main):001:0> puts "Hello, World"
109
+ Hello, World
110
+ => nil
111
+ irb(main):002:0> 1+2
112
+ => 3
113
+ Examples[edit]
114
+
115
+ The following examples can be run in a Ruby shell such as Interactive Ruby Shell, or saved in a file and run from the command line by typing ruby <filename>.
116
+ Classic Hello world example:
117
+ puts "Hello World!"
118
+ Some basic Ruby code:
119
+ # Everything, including a literal, is an object, so this works:
120
+ -199.abs # => 199
121
+ "ice is nice".length # => 11
122
+ "ruby is cool.".index("u") # => 1
123
+ "Nice Day Isn't It?".downcase.split("").uniq.sort.join # => " '?acdeinsty"
124
+ Conversions:
125
+ puts "Give me a number"
126
+ number = gets.chomp
127
+ puts number.to_i
128
+ output_number = number.to_i + 1
129
+ puts output_number.to_s + ' is a bigger number.'
130
+ Strings[edit]
131
+ There are a variety of ways to define strings in Ruby.
132
+ The following assignments are equivalent and support variable interpolation:
133
+ a = "\nThis is a double-quoted string\n"
134
+ a = %Q{\nThis is a double-quoted string\n}
135
+ a = %{\nThis is a double-quoted string\n}
136
+ a = %/\nThis is a double-quoted string\n/
137
+ a = <<-BLOCK
138
+
139
+ This is a double-quoted string
140
+ BLOCK
141
+ The following assignments are equivalent and produce raw strings:
142
+ a = 'This is a single-quoted string'
143
+ a = %q{This is a single-quoted string}
144
+ Collections[edit]
145
+ Constructing and using an array:
146
+ a = [1, 'hi', 3.14, 1, 2, [4, 5]]
147
+
148
+ a[2] # => 3.14
149
+ a.[](2) # => 3.14
150
+ a.reverse # => [[4, 5], 2, 1, 3.14, 'hi', 1]
151
+ a.flatten.uniq # => [1, 'hi', 3.14, 2, 4, 5]
152
+ Constructing and using an associative array (in Ruby, called a hash):
153
+ hash = Hash.new # equivalent to hash = {}
154
+ hash = { :water => 'wet', :fire => 'hot' } # makes the previous line redundant as we are now
155
+ # assigning hash to a new, separate hash object
156
+ puts hash[:fire] # prints "hot"
157
+
158
+ hash.each_pair do |key, value| # or: hash.each do |key, value|
159
+ puts "#{key} is #{value}"
160
+ end
161
+ # returns {:water=>"wet", :fire=>"hot"} and prints:
162
+ # water is wet
163
+ # fire is hot
164
+
165
+ hash.delete :water # deletes the pair :water => 'wet' and returns "wet"
166
+ hash.delete_if {|key,value| value == 'hot'} # deletes the pair :fire => 'hot' and returns {}
167
+ Blocks and iterators[edit]
168
+ The two syntaxes for creating a code block:
169
+ { puts "Hello, World!" } # note the braces
170
+ # or:
171
+ do
172
+ puts "Hello, World!"
173
+ end
174
+ A code block can be passed to a method as an optional block argument. Many built-in methods have such arguments:
175
+ File.open('file.txt', 'w') do |file| # 'w' denotes "write mode"
176
+ file.puts 'Wrote some text.'
177
+ end # file is automatically closed here
178
+
179
+ File.readlines('file.txt').each do |line|
180
+ puts line
181
+ end
182
+ # => Wrote some text.
183
+ Parameter-passing a block to be a closure:
184
+ # In an object instance variable (denoted with '@'), remember a block.
185
+ def remember(&a_block)
186
+ @block = a_block
187
+ end
188
+
189
+ # Invoke the preceding method, giving it a block which takes a name.
190
+ remember {|name| puts "Hello, #{name}!"}
191
+
192
+ # Call the closure:
193
+ @block.call("Jon") # => "Hello, Jon!"
194
+ Creating an anonymous function:
195
+ proc {|arg| puts arg}
196
+ Proc.new {|arg| puts arg}
197
+ lambda {|arg| puts arg}
198
+ ->(arg) {puts arg} # introduced in Ruby 1.9
199
+ Returning closures from a method:
200
+ def create_set_and_get(initial_value=0) # note the default value of 0
201
+ closure_value = initial_value
202
+ return Proc.new {|x| closure_value = x}, Proc.new { closure_value }
203
+ end
204
+
205
+ setter, getter = create_set_and_get # returns two values
206
+ setter.call(21)
207
+ getter.call # => 21
208
+
209
+ # Parameter variables can also be used as a binding for the closure,
210
+ # so the preceding can be rewritten as:
211
+
212
+ def create_set_and_get(closure_value=0)
213
+ return proc {|x| closure_value = x } , proc { closure_value }
214
+ end
215
+ Yielding the flow of program control to a block which was provided at calling time:
216
+ def use_hello
217
+ yield "hello"
218
+ end
219
+
220
+ # Invoke the preceding method, passing it a block.
221
+ use_hello {|string| puts string} # => 'hello'
222
+ Iterating over enumerations and arrays using blocks:
223
+ array = [1, 'hi', 3.14]
224
+ array.each {|item| puts item }
225
+ # prints:
226
+ # 1
227
+ # 'hi'
228
+ # 3.14
229
+
230
+ array.each_index {|index| puts "#{index}: #{array[index]}" }
231
+ # prints:
232
+ # 0: 1
233
+ # 1: 'hi'
234
+ # 2: 3.14
235
+
236
+ # The following uses a Range
237
+ (3..6).each {|num| puts num }
238
+ # prints:
239
+ # 3
240
+ # 4
241
+ # 5
242
+ # 6
243
+ A method such as inject can accept both a parameter and a block. The inject method iterates over each member of a list, performing some function on it while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:
244
+ [1,3,5].inject(10) {|sum, element| sum + element} # => 19
245
+ On the first pass, the block receives 10 (the argument to inject) as sum, and 1 (the first element of the array) as element. This returns 11, which then becomes sum on the next pass. It is added to 3 to get 14, which is then added to 5 on the third pass, to finally return 19.
246
+ Using an enumeration and a block to square the numbers 1 to 10 (using a range):
247
+ (1..10).collect {|x| x*x} # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
248
+ Or invoke a method on each item (map is a synonym for collect):
249
+ (1..5).map(&:to_f) # => [1.0, 2.0, 3.0, 4.0, 5.0]
250
+ Classes[edit]
251
+ The following code defines a class named Person. In addition to initialize, the usual constructor to create new objects, it has two methods: one to override the <=> comparison operator (so Array#sort can sort by age) and the other to override the to_s method (so Kernel#puts can format its output). Here, attr_reader is an example of metaprogramming in Ruby: attr_accessor defines getter and setter methods of instance variables, but attr_reader only getter methods. The last evaluated statement in a method is its return value, allowing the omission of an explicit return statement.
252
+ class Person
253
+ attr_reader :name, :age
254
+ def initialize(name, age)
255
+ @name, @age = name, age
256
+ end
257
+ def <=>(person) # the comparison operator for sorting
258
+ age <=> person.age
259
+ end
260
+ def to_s
261
+ "#{name} (#{age})"
262
+ end
263
+ end
264
+
265
+ group = [
266
+ Person.new("Bob", 33),
267
+ Person.new("Chris", 16),
268
+ Person.new("Ash", 23)
269
+ ]
270
+
271
+ puts group.sort.reverse
272
+ The preceding code prints three names in reverse age order:
273
+ Bob (33)
274
+ Ash (23)
275
+ Chris (16)
276
+ Person is a constant and is a reference to a Class object.
277
+ Open classes[edit]
278
+ In Ruby, classes are never closed: methods can always be added to an existing class. This applies to all classes, including the standard, built-in classes. All that is needed to do is open up a class definition for an existing class, and the new contents specified will be added to the existing contents. A simple example of adding a new method to the standard library's Time class:
279
+ # re-open Ruby's Time class
280
+ class Time
281
+ def yesterday
282
+ self - 86400
283
+ end
284
+ end
285
+
286
+ today = Time.now # => 2013-09-03 16:09:37 +0300
287
+ yesterday = today.yesterday # => 2013-09-02 16:09:37 +0300
288
+ Adding methods to previously defined classes is often called monkey-patching. However, if performed recklessly, this practice can lead to collisions of behavior and subsequent unexpected results, and problems with code scalability.
289
+ Exceptions[edit]
290
+ An exception is raised with a raise call:
291
+ raise
292
+ An optional message can be added to the exception:
293
+ raise "This is a message"
294
+ Exceptions can also be specified by the programmer:
295
+ raise ArgumentError, "Illegal arguments!"
296
+ Alternatively, an exception instance can be passed to the raise method:
297
+ raise ArgumentError.new("Illegal arguments!")
298
+ This last construct is useful when a custom exception class featuring a constructor which takes more than one argument needs to be raised:
299
+ class ParseError < Exception
300
+ def initialize input, line, pos
301
+ super "Could not parse '#{input}' at line #{line}, position #{pos}"
302
+ end
303
+ end
304
+
305
+ raise ParseError.new("Foo", 3, 9)
306
+ Exceptions are handled by the rescue clause. Such a clause can catch exceptions which inherit from StandardError. Other flow control keywords that can be used when handling exceptions are else and ensure:
307
+ begin
308
+ # do something
309
+ rescue
310
+ # handle exception
311
+ else
312
+ # do this if no exception was raised
313
+ ensure
314
+ # do this whether or not an exception was raised
315
+ end
316
+ It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:
317
+ begin
318
+ # do something
319
+ rescue Exception
320
+ # Exception handling code here.
321
+ # Don't write only "rescue"; that only catches StandardError, a subclass of Exception.
322
+ end
323
+ Or catch particular exceptions:
324
+ begin
325
+ # do something
326
+ rescue RuntimeError
327
+ # handle only RuntimeError and its subclasses
328
+ end
329
+ It is also possible to specify that the exception object be made available to the handler clause:
330
+ begin
331
+ # do something
332
+ rescue RuntimeError => e
333
+ # handling, possibly involving e, such as "puts e.to_s"
334
+ end
335
+ Alternatively, the most recent exception is stored in the magic global $!.
336
+ Several exceptions can also be caught:
337
+ begin
338
+ # do something
339
+ rescue RuntimeError, Timeout::Error => e
340
+ # handling, possibly involving e
341
+ end
342
+ Metaprogramming[edit]
343
+ Ruby code can programmatically modify, at runtime, aspects of its own structure that would be fixed in more rigid languages, such as class and method definitions. This sort of metaprogramming can be used to write more concise code and effectively extend the language.
344
+ For example, the following Ruby code generates new methods for the built-in String class, based on a list of colors. The methods wrap the contents of the string with an HTML tag styled with the respective color.
345
+ COLORS = { black: "000",
346
+ red: "f00",
347
+ green: "0f0",
348
+ yellow: "ff0",
349
+ blue: "00f",
350
+ magenta: "f0f",
351
+ cyan: "0ff",
352
+ white: "fff" }
353
+
354
+ class String
355
+ COLORS.each do |color,code|
356
+ define_method "in_#{color}" do
357
+ "<span style=\"color: ##{code}\">#{self}</span>"
358
+ end
359
+ end
360
+ end
361
+ The generated methods could then be used like this:
362
+ "Hello, World!".in_blue
363
+ => "<span style=\"color: #00f\">Hello, World!</span>"
364
+ To implement the equivalent in many other languages, the programmer would have to write each method (in_black, in_red, in_green, etc.) separately.
365
+ Some other possible uses for Ruby metaprogramming include:
366
+ intercepting and modifying method calls
367
+ implementing new inheritance models
368
+ dynamically generating classes from parameters
369
+ automatic object serialization
370
+ interactive help and debugging
371
+ More examples[edit]
372
+ More sample Ruby code is available as algorithms in the following articles:
373
+ Exponentiating by squaring
374
+ Trabb Pardo-Knuth algorithm
375
+ Implementations[edit]
376
+
377
+ See also: Ruby MRI#Operating systems
378
+ Ruby 1.9 has multiple implementations:
379
+ The official Ruby interpreter often referred to as the Matz's Ruby Interpreter or MRI. This implementation is written in C and uses its own Ruby-specific virtual machine,
380
+ JRuby, a Java implementation that runs on the Java virtual machine,
381
+ Rubinius, a C++ bytecode virtual machine that uses LLVM to compile to machine code at runtime. The bytecode compiler and most core classes are written in pure Ruby.
382
+ Other Ruby implementations:
383
+ MagLev (software), a Smalltalk implementation on VMware’s GemStone VM
384
+ MacRuby, an OS X implementation on the Objective-C runtime
385
+ Cardinal, an implementation for the Parrot virtual machine
386
+ IronRuby, an implementation on the .NET Framework
387
+ The maturity of Ruby implementations tends to be measured by their ability to run the Ruby on Rails (Rails) framework, because it is complex to implement and uses many Ruby-specific features. The point when a particular implementation achieves this goal is called "the Rails singularity". The reference implementation (MRI), JRuby, and Rubinius[43] are all able to run Rails unmodified in a production environment. IronRuby[44][45] is starting to be able to run Rails test cases, but is still far from being production-ready.
388
+ Ruby is available on many operating systems, such as Linux, Mac OS X, Microsoft Windows, Windows Phone,[46] Windows CE and most flavors of Unix.
389
+ Ruby 1.9 has recently been ported onto Symbian OS 9.x.[47]
390
+ Ruby can also run on embedded system by mruby, developing in GitHub.
391
+ Repositories and libraries[edit]
392
+
393
+ RubyGems is Ruby's package manager. A Ruby package is called a "gem" and can easily be installed via the command line. There are over 60,000 Ruby gems hosted on RubyGems.org.
394
+ Many new and existing Ruby libraries are hosted on GitHub, a service that offers version control repository hosting for Git.
395
+ See also[edit]
396
+
397
+ Portal icon Free software portal
398
+ Portal icon Computer programming portal
399
+ Comparison of programming languages
400
+ Ruby MRI, the reference C implementation
401
+ JRuby
402
+ MacRuby
403
+ IronRuby
404
+ Rubinius
405
+ MagLev
406
+ XRuby
407
+ Ruby on Rails
408
+ Why's (poignant) Guide to Ruby — an online ruby textbook in graphic novel format
409
+ Metasploit Project — the world's largest Ruby project, with over 700,000 lines of code
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: total_compressor
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.1.2
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2013-12-13 00:00:00.000000000 Z
12
+ date: 2013-12-14 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: bundler
@@ -101,15 +101,22 @@ extra_rdoc_files: []
101
101
  files:
102
102
  - .gitignore
103
103
  - Gemfile
104
+ - Gemfile.lock
104
105
  - LICENSE.txt
105
106
  - README.md
106
107
  - Rakefile
108
+ - bin/tcomp
107
109
  - lib/total_compressor.rb
110
+ - lib/total_compressor/compressors/base_compressor.rb
111
+ - lib/total_compressor/compressors/t_7z.rb
112
+ - lib/total_compressor/compressors/t_gzip.rb
113
+ - lib/total_compressor/compressors/t_rar.rb
114
+ - lib/total_compressor/compressors/t_zip.rb
108
115
  - lib/total_compressor/version.rb
109
116
  - spec/spec_helper.rb
110
117
  - spec/total_compressor_spec.rb
118
+ - test/text_file.txt
111
119
  - total_compressor.gemspec
112
- - bin/tcomp
113
120
  homepage: https://github.com/phlowerteam
114
121
  licenses:
115
122
  - MIT
@@ -125,7 +132,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
125
132
  version: '0'
126
133
  segments:
127
134
  - 0
128
- hash: -2772250057242909755
135
+ hash: -2986854980147011748
129
136
  required_rubygems_version: !ruby/object:Gem::Requirement
130
137
  none: false
131
138
  requirements:
@@ -134,7 +141,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
134
141
  version: '0'
135
142
  segments:
136
143
  - 0
137
- hash: -2772250057242909755
144
+ hash: -2986854980147011748
138
145
  requirements: []
139
146
  rubyforge_project:
140
147
  rubygems_version: 1.8.25
@@ -144,3 +151,4 @@ summary: Supports zip, gzip, rar, 7z archive types
144
151
  test_files:
145
152
  - spec/spec_helper.rb
146
153
  - spec/total_compressor_spec.rb
154
+ - test/text_file.txt