codify 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ *.swp
4
+ .bundle
5
+ .config
6
+ .yardoc
7
+ Gemfile.lock
8
+ InstalledFiles
9
+ _yardoc
10
+ coverage
11
+ doc/
12
+ lib/bundler/man
13
+ pkg
14
+ rdoc
15
+ spec/reports
16
+ test/tmp
17
+ test/version_tmp
18
+ tmp
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --colour
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in codify.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,181 @@
1
+ Copyright (c) 2012 Ronald Ping Man Chan
2
+
3
+ The Source Code Form referred to in this LICENSE file applies to all files stored within the same directory as this file, or in a subdirectory of the directory of this file, unless it is explicitly licensed or released otherwise. The official source of this software is found at https://github.com/ronalchn/.
4
+
5
+ This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ =============================================
8
+ A copy of the Mozilla Public License follows.
9
+ =============================================
10
+
11
+ Mozilla Public License
12
+ Version 2.0
13
+
14
+ 1. Definitions
15
+
16
+ 1.1. “Contributor”
17
+ means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
18
+
19
+ 1.2. “Contributor Version”
20
+ means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution.
21
+
22
+ 1.3. “Contribution”
23
+ means Covered Software of a particular Contributor.
24
+
25
+ 1.4. “Covered Software”
26
+ means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
27
+
28
+ 1.5. “Incompatible With Secondary Licenses”
29
+ means
30
+
31
+ that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
32
+
33
+ that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
34
+
35
+ 1.6. “Executable Form”
36
+ means any form of the work other than Source Code Form.
37
+
38
+ 1.7. “Larger Work”
39
+ means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. “License”
42
+ means this document.
43
+
44
+ 1.9. “Licensable”
45
+ means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
46
+
47
+ 1.10. “Modifications”
48
+ means any of the following:
49
+
50
+ any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
51
+
52
+ any new file in Source Code Form that contains any Covered Software.
53
+
54
+ 1.11. “Patent Claims” of a Contributor
55
+ means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
56
+
57
+ 1.12. “Secondary License”
58
+ means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
59
+
60
+ 1.13. “Source Code Form”
61
+ means the form of the work preferred for making modifications.
62
+
63
+ 1.14. “You” (or “Your”)
64
+ means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
65
+
66
+ 2. License Grants and Conditions
67
+
68
+ 2.1. Grants
69
+
70
+ Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
71
+
72
+ under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
73
+
74
+ under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
75
+
76
+ 2.2. Effective Date
77
+
78
+ The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.
79
+
80
+ 2.3. Limitations on Grant Scope
81
+
82
+ The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:
83
+
84
+ for any code that a Contributor has removed from Covered Software; or
85
+
86
+ for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
87
+
88
+ under Patent Claims infringed by Covered Software in the absence of its Contributions.
89
+
90
+ This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).
91
+
92
+ 2.4. Subsequent Licenses
93
+
94
+ No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).
95
+
96
+ 2.5. Representation
97
+
98
+ Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.
99
+
100
+ 2.6. Fair Use
101
+
102
+ This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.
103
+
104
+ 2.7. Conditions
105
+
106
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
107
+
108
+ 3. Responsibilities
109
+
110
+ 3.1. Distribution of Source Form
111
+
112
+ All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form.
113
+
114
+ 3.2. Distribution of Executable Form
115
+
116
+ If You distribute Covered Software in Executable Form then:
117
+
118
+ such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
119
+
120
+ You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License.
121
+
122
+ 3.3. Distribution of a Larger Work
123
+
124
+ You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).
125
+
126
+ 3.4. Notices
127
+
128
+ You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.
129
+
130
+ 3.5. Application of Additional Terms
131
+
132
+ You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
133
+
134
+ 4. Inability to Comply Due to Statute or Regulation
135
+
136
+ If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
137
+
138
+ 5. Termination
139
+
140
+ 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
141
+
142
+ 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
143
+
144
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
145
+
146
+ 6. Disclaimer of Warranty
147
+
148
+ Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
149
+
150
+ 7. Limitation of Liability
151
+
152
+ Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
153
+
154
+ 8. Litigation
155
+
156
+ Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims.
157
+
158
+ 9. Miscellaneous
159
+
160
+ This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
161
+
162
+ 10. Versions of the License
163
+
164
+ 10.1. New Versions
165
+
166
+ Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
167
+
168
+ 10.2. Effect of New Versions
169
+
170
+ You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
171
+
172
+ 10.3. Modified Versions
173
+
174
+ If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).
175
+
176
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
177
+
178
+ If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
179
+
180
+
181
+
@@ -0,0 +1,130 @@
1
+ # Codify
2
+
3
+ Transparently encodes text before saving to your database. Automatically encodes any desired text attributes for saving to database, and decodes when retrieving the field. Includes encoding for compression, encryption and error checking.
4
+
5
+ Many encodings can be useful, for example, compression can be useful for large text fields, to save disk space, encryption may be used to safeguard data.
6
+
7
+ This is not suitable if you plan to do fulltext searching directly on encoded attributes, although it can still be used where a separate fulltext search engine is used.
8
+
9
+ Currently, only activerecord is supported.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application''s Gemfile:
14
+
15
+ gem 'codify'
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install codify
24
+
25
+ ## Usage
26
+
27
+ In general, to encode an attribute, just call `attr_encoder` on the attribute:
28
+
29
+ ```ruby
30
+ class DataBlock < ActiveRecord::Base
31
+ attr_encoder :data, :encoder => :base64
32
+ end
33
+ ```
34
+
35
+ Codify will now expect to save data to an <tt>encoded_data</tt> field. So you should add the column via a migration. Notice that we can now to save binary data to the database, and can use a text type, because of the <tt>Base64Encoder</tt>.
36
+
37
+ ```ruby
38
+ add_column :data_blocks, :encoded_data, :text
39
+ ```
40
+
41
+ Now, you can easily read or write, and leave the encoding and decoding to Codify.
42
+
43
+ ```ruby
44
+ # writing
45
+ datablock = DataBlock.create(:data => "Data, could be binary, like these: \0\x43!")
46
+
47
+ # reading
48
+ datablock = DataBlock.first
49
+ datablock.data # => "Data, could be binary, ..."
50
+ ```
51
+
52
+ A convenience method <tt>attr_compressor</tt> is also available to compress an attribute.
53
+
54
+ ```ruby
55
+ class Page < ActiveRecord::Base
56
+ attr_compressor :body #, :encoder => :zlib # this is already the default for attr_compressor
57
+ end
58
+ ```
59
+
60
+ ### Options
61
+
62
+ Options can be passed to some encoders. The exact options possible depend on the encoder. Probably the easiest way is just to pass them to <tt>attr_encoder</tt> when an encoded attribute is declared.
63
+
64
+ ```ruby
65
+ attr_compressor :body, :encoder => :zlib, :level => 9 # highest possible compression
66
+ ```
67
+
68
+ They can also be passed when initializing an encoder object:
69
+
70
+ ```ruby
71
+ attr_compressor :body, :encoder => Codify::Encoders::ZlibEncoder.new(:level => 9)
72
+ ```
73
+
74
+ ### Chaining Encoders
75
+
76
+ A number of encoders can be chained, to apply them one after the other for a single attribute.
77
+
78
+ ```ruby
79
+ class Page < ActiveRecord::Base
80
+ attr_compressor :body, :encoder => [:zlib, :base64]
81
+ end
82
+ ```
83
+
84
+ This will first compress with <tt>ZlibEncoder</tt>, then encode the resulting binary with <tt>Base64Encoder</tt>.
85
+
86
+ ### Custom Encoders
87
+
88
+ If the included encoders are not sufficient, you can use your own, just inherit from <tt>Codify::Encoders::AbstractEncoder</tt>, and define <tt>encode</tt> and <tt>decode</tt> methods. To use options which may be passed to the encoder, just call <tt>options</tt> with a symbol.
89
+
90
+ ```ruby
91
+ class MyEncoder < Codify::Encoders::AbstractEncoder
92
+ def encode(data)
93
+ "#{options(:header)}#{data}#{options(:footer)}" # wrap data in header and footer
94
+ end
95
+ def decode(data)
96
+ data[options(:header).length...options(:footer).length] # remove header and footer from data
97
+ end
98
+ end
99
+ class Model < ActiveRecord::Base
100
+ attr_encoder :data, :encoder => MyEncoder
101
+ end
102
+ ```
103
+
104
+ Instead of passing a class to <tt>attr_encoder</tt>, it is also possible to register custom encoders with a symbol.
105
+
106
+ ```ruby
107
+ Codify::Encoders.register :my_encoder, MyEncoder, :encoding
108
+ class Model < ActiveRecord::Base
109
+ attr_encoder :data, :encoder => :my_encoder, :encoder_type => :encoding
110
+ end
111
+ ```
112
+
113
+ The <tt>:encoder_type</tt> option specifies a registration namespace which will be searched first for <tt>:my_encoder</tt>. The global registration namespace will only be searched after a specific namespace does not include the desired encoder. This can be useful if multiple encoders are given the same name. If they are in different namespaces, the can still be specified.
114
+
115
+ An encoder may also be registered by passing a block to <tt>register</tt>. This can be used to dynamically register a set of symbols.
116
+
117
+ ```ruby
118
+ Codify::Encoders.register MyEncoder do |symbol|
119
+ return MyEncoder if [:myencoder, :my_encoder, :MYENCODER].include?(symbol)
120
+ nil # if symbol is not found, return nil
121
+ end
122
+ ```
123
+
124
+ ## Contributing
125
+
126
+ 1. Fork it
127
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
128
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
129
+ 4. Push to the branch (`git push origin my-new-feature`)
130
+ 5. Create new Pull Request
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
@@ -0,0 +1,27 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/codify/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Ronald Ping Man Chan"]
6
+ gem.email = ["ronalchn@gmail.com"]
7
+ gem.description = %q{Transparently encodes text before saving to your database.}
8
+ gem.summary = %q{Automatically encodes any desired text attributes for saving to database, and unencodes when retrieving the field. Includes encoding for compression, encryption and error checking.}
9
+ gem.homepage = "https://github.com/ronalchn/codify"
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "codify"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = Codify::VERSION
17
+
18
+ # specify any dependencies here; for example:
19
+ gem.add_development_dependency "rake"
20
+ gem.add_development_dependency "rspec"
21
+ gem.add_development_dependency "sqlite3"
22
+ gem.add_development_dependency "database_cleaner"
23
+ gem.add_development_dependency "debugger"
24
+ gem.add_development_dependency "datamapper"
25
+
26
+ gem.add_runtime_dependency "activerecord", '>= 3.0'
27
+ end
@@ -0,0 +1,19 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require "codify/version"
8
+ require "codify/model_additions"
9
+
10
+ require "codify/encoders.rb"
11
+
12
+ require "codify/model_adapters/abstract_adapter"
13
+ require "codify/model_adapters/active_record_adapter" if defined? ActiveRecord
14
+ # require "codify/model_adapters/datamapper_adapter" if defined? DataMapper
15
+ require "codify/railtie" if defined? Rails::Railtie
16
+
17
+ module Codify
18
+
19
+ end
@@ -0,0 +1,99 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require "codify/encoders/abstract_encoder"
8
+ require "codify/encoders/zlib_encoder"
9
+ require "codify/encoders/base64_encoder"
10
+
11
+ module Codify
12
+ module Encoders
13
+
14
+ # A hash of hashes of the encoders that have been registered. The first level represents the
15
+ # encoder type, the second level maps the symbol of an encoder, to the encoder class.
16
+ @@registry = {:all => {}} # :nodoc:
17
+
18
+ # Registers a symbol to an encoder class. This allows a symbol to be used to refer to the encoder
19
+ # that should be used to encoding/decoding.
20
+ #
21
+ # Codify::Encoders.register(symbol, encoder_class, type)
22
+ #
23
+ # The type parameter takes a single symbol, or array of symbols, representing the encoder type(s)
24
+ # that the encoder can be classified under. All encoders are classified under :all, so this symbol
25
+ # should not be passed in explicitly. If not specified, an empty array is assumed.
26
+ #
27
+ # Alternatively a block can be passed, which may represent a whole set of symbols. The block should
28
+ # take a single symbol, and decide to return an encoder class (representing a successful match), or
29
+ # nil (representing an unsuccessful match). For example:
30
+ #
31
+ # Codify::Encoders.register(:compressor) do |symbol|
32
+ # { :zlib => Codify::Encoders::ZlibEncoder }[symbol] # returns nil if symbol not found
33
+ # end
34
+ #
35
+ # Where the same symbol is used within the same type for different encoders, precedence favours
36
+ # encoders registered later. Additionally, all encoders registered via a block will have lower
37
+ # precedence than encoders registered by a fixed symbol.
38
+ #
39
+ def self.register symbol, klass = nil, type = nil, &block
40
+ raise ArgumentError, "wrong number of arguments (1 for 2)" if klass.nil? && !block_given?
41
+ type = symbol if block_given?
42
+ Array(type).map(&:to_sym).push(:all).each do |type|
43
+ @@registry[type] ||= {} # ensure registry type initialized
44
+ if block_given?
45
+ (@@registry[type][0] ||= []).push(block)
46
+ else
47
+ @@registry[type][symbol.to_sym] = klass
48
+ end
49
+ end
50
+ end
51
+
52
+ # Finds the encoder class that a symbol is registered for. The encoder type can be set to give
53
+ # precedence to a particular type of encoder that is searched first. This is relevant in case
54
+ # of symbol collisions.
55
+ #
56
+ # If already a class or object which may be an Encoder (not a symbol), uses the input encoder.
57
+ #
58
+ # If it is a class, initialize the Encoder with input options
59
+ #
60
+ def self.find encoder, type = :all, options # :nodoc:
61
+ return encoder if encoder.class < AbstractEncoder
62
+ unless encoder.class == Class || encoder.class < AbstractEncoder
63
+ symbol = encoder.to_sym
64
+ @@registry[type] ||= {}
65
+ unless type == :all
66
+ encoder = @@registry[type][symbol]
67
+ encoder ||= @@registry[type][0].reverse_each.reduce(nil) { |encoder,f| encoder || f[symbol] } if @@registry[type].has_key?(0)
68
+ end
69
+ encoder ||= @@registry[:all][symbol]
70
+ encoder ||= @@registry[:all][0].reverse_each.reduce(nil) { |encoder,f| encoder || f[symbol] } if @@registry[:all].has_key?(0)
71
+ raise KeyError, ":#{symbol} encoder of type :#{type || :all} not found" if encoder.nil?
72
+ end
73
+ encoder = encoder.new(options) if encoder.class === Class && encoder < AbstractEncoder
74
+ encoder
75
+ end
76
+
77
+ def self.encode encoders, data
78
+ encoders.each do |encoder|
79
+ data = encoder.encode(data)
80
+ end
81
+ data
82
+ end
83
+
84
+ def self.decode encoders, data
85
+ encoders.reverse_each do |encoder|
86
+ data = encoder.decode(data)
87
+ end
88
+ data
89
+ end
90
+
91
+ # register default encoders
92
+ register :zlib, ZlibEncoder, :compressor
93
+ register :base64, Base64Encoder, :encoding
94
+ register :strict_base64, Base64Encoder.new( :representation => :strict ), :encoding
95
+ register :urlsafe_base64, Base64Encoder.new( :representation => :urlsafe ), :encoding
96
+ register :none, AbstractEncoder # TODO: add a plaintext encoder
97
+
98
+ end
99
+ end
@@ -0,0 +1,77 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module Encoders
9
+ class AbstractEncoder
10
+ # Assigns options to instance variable
11
+ #
12
+ def initialize options = {}
13
+ @options = options.symbolize_keys
14
+ end
15
+
16
+ # Allow a record to be linked to this encoder (for procs)
17
+ #
18
+ def record= record
19
+ @record = record
20
+ end
21
+
22
+ # Encoders derived from AbstractEncoder should re-implement encode and optionally
23
+ # decode.
24
+ #
25
+ def encode data
26
+ raise NotImplementedError, "Error: #{self.class.name}.encode not implemented!"
27
+ end
28
+
29
+ # Detects whether this encoder can be reversed
30
+ #
31
+ def decodes?
32
+ respond_to?(:decode)
33
+ end
34
+
35
+ # Detects whether any options depend on record attributes. This has implications on the attribute interface.
36
+ # If state information like keys or similar are not constant, then there cannot exist a class method
37
+ # to encode or decode data (ie. encoding must be done on an instance).
38
+ #
39
+ def depends_on_record?
40
+ @options.any? { |option| option.class === Proc || option.class === Symbol }
41
+ end
42
+
43
+ # Wrapper to easily use encoder for encoding, by automatically constructing one
44
+ #
45
+ def self.encode data, options = {}, record = nil
46
+ encoder = new(options)
47
+ encoder.record = record
48
+ encoder.encode(data)
49
+ end
50
+
51
+ # Wrapper to easily use encoder for decoding, by automatically constructing one
52
+ #
53
+ def self.decode data, options = {}, record = nil
54
+ encoder = new(options)
55
+ encoder.record = record
56
+ encoder.decode(data)
57
+ end
58
+
59
+ private
60
+ # Reads the option - executing if it is a Proc
61
+ #
62
+ def options key
63
+ value = @options[key]
64
+ if value.class === Proc
65
+ if value.arity == 0
66
+ value = value.call
67
+ else
68
+ value = value.call(@record)
69
+ end
70
+ end
71
+ value = @record.send(value) if value.class === Symbol
72
+ value
73
+ end
74
+
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,24 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module Encoders
9
+ class Base64Encoder < AbstractEncoder
10
+ def encode data
11
+ Base64.send method_name(options(:representation),:encode64), data
12
+ end
13
+
14
+ def decode data
15
+ Base64.send method_name(options(:representation),:decode64), data
16
+ end
17
+
18
+ private
19
+ def method_name representation, suffix
20
+ ({ :strict => "strict_", :urlsafe => "urlsafe_" }[representation.try(&:to_sym)] || "") + "#{suffix}"
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,24 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module Encoders
9
+ class ZlibEncoder < AbstractEncoder
10
+ def encode data
11
+ level = options(:level) || Zlib::DEFAULT_COMPRESSION
12
+
13
+ deflator = Zlib::Deflate.new(level)
14
+ # deflator.set_dictionary(options[:dictionary]) if options.has_key? :dictionary
15
+ deflator.deflate(data.to_s, Zlib::FINISH)
16
+ end
17
+
18
+ def decode data
19
+ inflator = Zlib::Inflate.new
20
+ inflator.inflate(data)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module ModelAdapters
9
+ class AbstractAdapter
10
+ # def
11
+ # end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,15 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module ModelAdapters
9
+ class ActiveRecordAdapter < AbstractAdapter
10
+ # def
11
+ # end
12
+ end
13
+ end
14
+ end
15
+
@@ -0,0 +1,131 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ module ModelAdditions
9
+
10
+ def self.included(base)
11
+ base.extend ClassMethods
12
+ end
13
+
14
+ module ClassMethods
15
+ def attr_compressor attribute_name, options = {}
16
+ options = { :encoder => :zlib, :prefix => "compressed_", :verb => "compress", :reverse_verb => "uncompress", :encoder_type => :compressor }.merge(options.symbolize_keys)
17
+ attr_encoder attribute_name, options
18
+ end
19
+
20
+ def attr_encoder attribute_name, options = {}
21
+ options = { :encoder => :none, :prefix => "encoded_", :suffix => "", :verb => "encode", :reverse_verb => "decode" }.merge(options.symbolize_keys)
22
+ # manage options, extract those required (the rest will be passed to individual encoders)
23
+ encoder_type = options.delete(:encoder_type)
24
+ encoders = Array(options.delete(:encoder))
25
+ prefix = options.delete(:prefix)
26
+ suffix = options.delete(:suffix)
27
+ verb = options.delete(:verb)
28
+ reverse_verb = options.delete(:reverse_verb)
29
+
30
+ encoders.map! { |encoder| Encoders.find(encoder, encoder_type, options) }
31
+ # give encoders a reference to the record if they require it
32
+ encoders.each { |encoder| encoder.record = self if encoder.depends_on_record? }
33
+
34
+ # some constant variables (for naming purposes)
35
+ attribute_name = attribute_name.to_sym
36
+ encoded_attribute_name = options.has_key?(:attribute) ? options.delete(:attribute) : "#{prefix}#{attribute_name}#{suffix}".to_sym
37
+ unencoded_ivar = "@_un#{encoded_attribute_name}".to_sym
38
+ old_unencoded_ivar = "@_old_un#{encoded_attribute_name}".to_sym
39
+
40
+ # flags
41
+ has_unencoded = attribute_names.include? attribute_name.to_s # check if (legacy) unencoded attribute still exists
42
+ depends_on_record = encoders.any? { |encoder| encoder.depends_on_record? } # then no class method to encode this attribute
43
+ reversible = encoders.all? { |encoder| encoder.decodes? } # then no reading of encoded attributes
44
+
45
+ define_method attribute_name do # override where to read it from
46
+ value = instance_variable_get unencoded_ivar
47
+ if value.nil? # if uninitialized
48
+ encoded_value = read_attribute(encoded_attribute_name)
49
+ if reversible && !encoded_value.blank?
50
+ value = Encoders.decode(encoders, encoded_value)
51
+ elsif has_unencoded
52
+ value = read_attribute(attribute_name)
53
+ end
54
+ instance_variable_set unencoded_ivar, value # initialize
55
+ end
56
+ value
57
+ end
58
+
59
+ define_method "#{attribute_name}=".to_sym do |value|
60
+ encoded_value = Encoders.encode(encoders, value)
61
+ if !send("#{encoded_attribute_name}_changed?") # implement a little bit of ActiveModel::Dirty on unencoded variable (for caching)
62
+ instance_variable_set(old_unencoded_ivar, instance_variable_get(unencoded_ivar))
63
+ end
64
+ write_attribute(encoded_attribute_name, encoded_value)
65
+ instance_variable_set unencoded_ivar, value # save a copy of the unencoded value
66
+ end
67
+
68
+ define_method "#{attribute_name}_changed?".to_sym do
69
+ send("#{encoded_attribute_name}_changed?")
70
+ end
71
+
72
+ define_method "#{attribute_name}_was".to_sym do # use cached old unencoded variable if available
73
+ instance_variable_get(old_unencoded_ivar) || begin
74
+ encoded_value = send("#{encoded_attribute_name}_was")
75
+ next (has_unencoded ? read_attribute(attribute_name) : nil) if encoded_value.blank?
76
+ value = Encoders.decode(encoders, encoded_value)
77
+ instance_variable_set(old_unencoded_ivar, value) # cache what has been decoded
78
+ end
79
+ end if reversible # do not define method if cannot decode
80
+
81
+ define_method "#{attribute_name}_change".to_sym do
82
+ send("#{encoded_attribute_name}_changed?") ? [send("#{attribute_name}_was"), send(attribute_name)] : nil
83
+ end if reversible
84
+
85
+ define_method "#{attribute_name}?".to_sym do
86
+ if reversible
87
+ value = send attribute_name
88
+ else
89
+ value = send encoded_attribute_name
90
+ end
91
+ value && !value.blank?
92
+ end
93
+
94
+ after_initialize do |record| # eager decoding attribute in case other record states change (affecting encoding)
95
+ encoded_value = read_attribute(encoded_attribute_name)
96
+ instance_variable_set unencoded_ivar, Encoders.decode(encoders, encoded_value) unless encoded_value.blank?
97
+ end if reversible && depends_on_record
98
+
99
+ before_save do |record|
100
+ # if writing a new encoded value, clear unencoded value if necessary
101
+ write_attribute(attribute_name, "") if has_unencoded && record.send("#{encoded_attribute_name}_changed?")
102
+
103
+ # re-encode if states could have changed, and encoding might depend on those states
104
+ # WARNING: if users change the state in another before_save callback after this executes, inconsistent state
105
+ # might still result
106
+ if depends_on_record && self.changed?
107
+ value = send(attribute_name)
108
+ write_attribute(encoded_attribute_name, Encoders.encode(encoders, value))
109
+ end
110
+ true
111
+ end
112
+
113
+ define_method "#{encoded_attribute_name}=".to_sym do |value| # don't let users set encoded value manually (because it is dangerous)
114
+ raise NoMethodError, "undefined method '#{encoded_attribute_name}=' for #{self}"
115
+ end
116
+
117
+ # define class methods
118
+ (class << self; self; end).instance_eval do
119
+ define_method [verb,attribute_name].join('_').to_sym do |data|
120
+ Encoders.encode(encoders,data)
121
+ end
122
+
123
+ define_method [reverse_verb,attribute_name].join('_').to_sym do |data|
124
+ Encoders.decode(encoders,data)
125
+ end
126
+ end if !depends_on_record
127
+ end
128
+ end
129
+ end
130
+ end
131
+
@@ -0,0 +1,21 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ module Codify
8
+ class Railtie < ::Rails::Railtie
9
+ initializer 'codify.model_additions' do
10
+ ActiveSupport.on_load(:active_record) do
11
+ include Codify::ModelAdditions
12
+ end
13
+
14
+ # initialize other persistent models
15
+
16
+ # if defined? ::DataMapper
17
+ # ::DataMapper::Model.append_extensions(Codify::ModelAdditions)
18
+ # end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,3 @@
1
+ module Codify
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,52 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require 'spec_helper'
8
+
9
+ describe 'Base64Token' do
10
+ before(:all) do
11
+ ActiveRecord::Base.connection.create_table :base64_tokens do |t|
12
+ t.string :encoded_token
13
+ t.string :encoded_url_token
14
+ t.timestamps
15
+ end
16
+ class Base64Token < ActiveRecord::Base
17
+ include Codify::ModelAdditions
18
+ attr_encoder :token, :encoder => :base64
19
+ attr_encoder :url_token, :encoder => :base64, :representation => :urlsafe
20
+ end
21
+ end
22
+ after(:all) do
23
+ ActiveRecord::Base.connection.drop_table :base64_tokens
24
+ end
25
+
26
+ it 'can set base64 token' do
27
+ base64_token = Base64Token.new
28
+ token = "Important key information"
29
+ base64_token.token = token
30
+ base64_token.token.should == token
31
+ base64_token.encoded_token.should_not == token
32
+ Base64Token.encode_token(token) == base64_token.encoded_token
33
+ end
34
+ it 'can set url safe base64 token' do
35
+ base64_token = Base64Token.new
36
+ token = "Important key information"
37
+ base64_token.url_token = token
38
+ base64_token.url_token.should == token
39
+ base64_token.encoded_url_token.should_not == token
40
+ Base64Token.encode_url_token(token) == base64_token.encoded_url_token
41
+ end
42
+ it 'base64 and url safe base64 are not the same' do
43
+ token = "Important key information"
44
+ Base64Token.encode_url_token(token).should_not == Base64Token.encode_token(token)
45
+ end
46
+ it 'can decode token' do
47
+ token = "Important key information"
48
+ base64_token = Base64Token.create(:token => token)
49
+ base64_token = Base64Token.find(base64_token.id)
50
+ base64_token.token.should == token
51
+ end
52
+ end
@@ -0,0 +1,56 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require 'spec_helper'
8
+
9
+ describe 'CompressedBase64Email' do
10
+ before(:all) do
11
+ ActiveRecord::Base.connection.create_table :compressed_base64_emails do |t|
12
+ t.string :from
13
+ t.string :to
14
+ t.string :subject
15
+ t.text :compressed_body
16
+ end
17
+ class CompressedBase64Email < ActiveRecord::Base
18
+ include Codify::ModelAdditions
19
+ attr_compressor :body, :encoder => [:zlib,:base64], :representation => :strict
20
+ end
21
+ end
22
+ after(:all) do
23
+ ActiveRecord::Base.connection.drop_table :compressed_base64_emails
24
+ end
25
+
26
+ it 'can set compressed body' do
27
+ email = CompressedBase64Email.new
28
+ body = "My new email body"
29
+ email.body = body
30
+ email.body.should == body
31
+ email.body_changed?.should be_true
32
+ end
33
+ it 'can construct and compress new email with body' do
34
+ body = "My email body set on initialization"
35
+ email = CompressedBase64Email.new( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Test", :body => body )
36
+ email.body_changed?.should be_true
37
+ email.compressed_body_changed?.should be_true
38
+ email.compressed_body.should_not be_blank
39
+ end
40
+ it 'can save email with compressed body and uncompress the body again' do
41
+ body = "My email body set on initialization"
42
+ email = CompressedBase64Email.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Test", :body => body )
43
+ email = CompressedBase64Email.find(email.id)
44
+ email.body.should == body
45
+ end
46
+ it 'compresses body correctly' do
47
+ email = CompressedBase64Email.new
48
+ body = "My new email body"
49
+ email.body = body
50
+ CompressedBase64Email.uncompress_body(email.compressed_body).should == body
51
+ end
52
+ it 'is printable once compressed' do
53
+ compressed_body = CompressedBase64Email.compress_body("Test compression")
54
+ compressed_body.inspect.should == "\"#{compressed_body}\"" # because it is printable
55
+ end
56
+ end
@@ -0,0 +1,110 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require 'spec_helper'
8
+
9
+ describe 'CompressedEmail' do
10
+ before(:all) do
11
+ ActiveRecord::Base.connection.create_table :compressed_emails do |t|
12
+ t.string :from
13
+ t.string :to
14
+ t.string :subject
15
+ t.binary :compressed_body
16
+ end
17
+ class CompressedEmail < ActiveRecord::Base
18
+ include Codify::ModelAdditions
19
+ attr_compressor :body
20
+ end
21
+ end
22
+ after(:all) do
23
+ ActiveRecord::Base.connection.drop_table :compressed_emails
24
+ end
25
+
26
+ it 'reading body is nil for new email' do
27
+ email = CompressedEmail.new
28
+ email.body.should be_nil
29
+ end
30
+ it 'can set compressed body' do
31
+ email = CompressedEmail.new
32
+ body = "My new email body"
33
+ email.body = body
34
+ email.body.should == body
35
+ email.body_changed?.should be_true
36
+ end
37
+ it 'body initially unchanged' do
38
+ email = CompressedEmail.new
39
+ email.body_changed?.should be_false
40
+ end
41
+ it 'cannot set compressed body attribute directly' do
42
+ email = CompressedEmail.new
43
+ expect do
44
+ email.compressed_body = "My new body" # throws NoMethodError exception
45
+ end.to raise_exception(NoMethodError)
46
+ end
47
+ it 'changes compressed body when body changed' do
48
+ email = CompressedEmail.new
49
+ email.compressed_body.should be_blank
50
+ email.body = "My new email body"
51
+ email.compressed_body.should_not be_blank
52
+ email.compressed_body_changed?.should be_true
53
+ end
54
+ it 'can construct and compress new email with body' do
55
+ body = "My email body set on initialization"
56
+ email = CompressedEmail.new( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Test initialization compression", :body => body )
57
+ email.body_changed?.should be_true
58
+ email.compressed_body_changed?.should be_true
59
+ email.compressed_body.should_not be_blank
60
+ end
61
+ it 'can save email with compressed body' do
62
+ body = "My email body set on initialization"
63
+ email = CompressedEmail.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Test initialization compression", :body => body )
64
+ email = CompressedEmail.find(email.id)
65
+ email.body.should == body
66
+ end
67
+ it 'can compress body to use less space' do
68
+ body = "I will use less space. I will use less space. I will use less space. I will use less space... how many more lines should I write?"
69
+ email = CompressedEmail.new( :body => body )
70
+ email.compressed_body.length.should < body.length
71
+ end
72
+ it 'compresses on record and ActiveRecord class the same' do
73
+ body = "I can be compressed by class and object"
74
+ email = CompressedEmail.new( :body => body )
75
+ CompressedEmail.compress_body(body).should == email.compressed_body
76
+ end
77
+ it 'uncompresses on record and ActiveRecord class the same' do
78
+ body = "I can be uncompressed by class and object"
79
+ email = CompressedEmail.new( :body => body )
80
+ CompressedEmail.uncompress_body(email.compressed_body).should == body
81
+ end
82
+ context 'with email already in database' do
83
+ before(:each) do
84
+ @body = "Initial body that is in the database. I am very happy in the database, after I have been compressed, I can be re-inflated."
85
+ @email_id = CompressedEmail.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Email in database", :body => @body ).id
86
+ end
87
+ it 'can read back body' do
88
+ email = CompressedEmail.find(@email_id)
89
+ email.body.should == @body
90
+ email.body_changed?.should be_false
91
+ end
92
+ it 'can change body and save' do
93
+ email = CompressedEmail.find(@email_id)
94
+ email.body = "My new body"
95
+ email.compressed_body_changed?.should be_true
96
+ email.save
97
+ email.reload.body.should_not == @body
98
+ end
99
+ it 'body_change shows change in body' do
100
+ email = CompressedEmail.find(@email_id)
101
+ email.body_change.should be_nil
102
+ email.body = "My new body"
103
+ email.body_change.should == [@body,email.body]
104
+ email.body = "Another body"
105
+ email.body_change.should == [@body,email.body]
106
+ email.body = @body
107
+ email.body_change.should be_nil
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,76 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require 'spec_helper'
8
+
9
+ # this spec checks that an ActiveRecord model with a legacy un-compressed column which should now be compressed
10
+ # will still work appropriately - compressing the column for new objects, even as the original object's columns
11
+ # are left un-compressed
12
+
13
+ describe 'CompressedLegacyEmail' do
14
+ before(:all) do
15
+ ActiveRecord::Base.connection.create_table :legacy_emails do |t|
16
+ t.string :from
17
+ t.string :to
18
+ t.string :subject
19
+ t.text :body # legacy column for old uncompressed bodies
20
+ t.binary :compressed_body # new column for compressed bodies
21
+ end
22
+ class LegacyEmail < ActiveRecord::Base # used to test data with direct access to database
23
+ end
24
+ class CompressedLegacyEmail < LegacyEmail
25
+ include Codify::ModelAdditions
26
+ attr_compressor :body
27
+ end
28
+ end
29
+ after(:all) do
30
+ ActiveRecord::Base.connection.drop_table :legacy_emails
31
+ end
32
+
33
+ it 'reading body is nil for new email' do
34
+ email = CompressedLegacyEmail.new
35
+ email.body.should be_nil
36
+ end
37
+ it 'body initially unchanged' do
38
+ email = CompressedLegacyEmail.new
39
+ email.body_changed?.should be_false
40
+ email.body_change.should be_nil
41
+ end
42
+ it 'cannot set compressed body attribute directly' do
43
+ email = CompressedLegacyEmail.new
44
+ expect do
45
+ email.compressed_body = "My new body" # throws NoMethodError exception
46
+ end.to raise_exception(NoMethodError)
47
+ end
48
+ it 'can save email with compressed body only' do
49
+ body = "My email body set on initialization"
50
+ email = CompressedLegacyEmail.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Test initialization compression", :body => body )
51
+ email = CompressedLegacyEmail.find(email.id) # re-load from database
52
+ email.body.should == body
53
+ # check that only compressed body is saved
54
+ legacy_email = LegacyEmail.find(email.id)
55
+ legacy_email.body.should be_blank
56
+ legacy_email.compressed_body.should_not be_blank
57
+ end
58
+ it 'can read legacy email with uncompressed body' do
59
+ body = "My email body set on initialization"
60
+ legacy_email = LegacyEmail.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Uncompressed email", :body => body )
61
+ legacy_email.compressed_body.should be_nil
62
+ email = CompressedLegacyEmail.find(legacy_email.id)
63
+ email.body.should == body
64
+ end
65
+ it 'can save compressed body for initially uncompressed legacy email' do
66
+ body = "My email body set on initialization"
67
+ legacy_email = LegacyEmail.create( :from => "initializer@email.class", :to => "codify@email.class", :subject => "Uncompressed email", :body => body )
68
+ email = CompressedLegacyEmail.find(legacy_email.id)
69
+ new_body = "New body which will be compressed!"
70
+ email.body = new_body
71
+ email.save
72
+ legacy_email.reload.body.should be_blank
73
+ legacy_email.compressed_body.should_not be_blank
74
+ email.reload.body.should == new_body
75
+ end
76
+ end
@@ -0,0 +1,35 @@
1
+ # Copyright (c) 2012 Ronald Ping Man Chan
2
+ #
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ require 'active_record'
8
+ require 'rspec'
9
+ require 'rake'
10
+ require 'database_cleaner'
11
+ require 'codify'
12
+
13
+ # Load support files
14
+ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
15
+
16
+ RSpec.configure do |config|
17
+ config.before(:suite) do
18
+ ActiveRecord::Base.establish_connection(
19
+ :adapter => "sqlite3",
20
+ :database => ":memory:"
21
+ )
22
+
23
+ DatabaseCleaner.strategy = :transaction
24
+ DatabaseCleaner.clean_with(:truncation)
25
+ end
26
+
27
+ config.before(:each) do
28
+ DatabaseCleaner.start
29
+ end
30
+
31
+ config.after(:each) do
32
+ DatabaseCleaner.clean
33
+ end
34
+ end
35
+
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: codify
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Ronald Ping Man Chan
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-09-07 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rake
16
+ requirement: &10378180 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: *10378180
25
+ - !ruby/object:Gem::Dependency
26
+ name: rspec
27
+ requirement: &10375740 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: *10375740
36
+ - !ruby/object:Gem::Dependency
37
+ name: sqlite3
38
+ requirement: &10390500 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ! '>='
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ type: :development
45
+ prerelease: false
46
+ version_requirements: *10390500
47
+ - !ruby/object:Gem::Dependency
48
+ name: database_cleaner
49
+ requirement: &10388660 !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ! '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ type: :development
56
+ prerelease: false
57
+ version_requirements: *10388660
58
+ - !ruby/object:Gem::Dependency
59
+ name: debugger
60
+ requirement: &10385200 !ruby/object:Gem::Requirement
61
+ none: false
62
+ requirements:
63
+ - - ! '>='
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ type: :development
67
+ prerelease: false
68
+ version_requirements: *10385200
69
+ - !ruby/object:Gem::Dependency
70
+ name: datamapper
71
+ requirement: &10383440 !ruby/object:Gem::Requirement
72
+ none: false
73
+ requirements:
74
+ - - ! '>='
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ type: :development
78
+ prerelease: false
79
+ version_requirements: *10383440
80
+ - !ruby/object:Gem::Dependency
81
+ name: activerecord
82
+ requirement: &10394280 !ruby/object:Gem::Requirement
83
+ none: false
84
+ requirements:
85
+ - - ! '>='
86
+ - !ruby/object:Gem::Version
87
+ version: '3.0'
88
+ type: :runtime
89
+ prerelease: false
90
+ version_requirements: *10394280
91
+ description: Transparently encodes text before saving to your database.
92
+ email:
93
+ - ronalchn@gmail.com
94
+ executables: []
95
+ extensions: []
96
+ extra_rdoc_files: []
97
+ files:
98
+ - .gitignore
99
+ - .rspec
100
+ - Gemfile
101
+ - LICENSE
102
+ - README.md
103
+ - Rakefile
104
+ - codify.gemspec
105
+ - lib/codify.rb
106
+ - lib/codify/encoders.rb
107
+ - lib/codify/encoders/abstract_encoder.rb
108
+ - lib/codify/encoders/base64_encoder.rb
109
+ - lib/codify/encoders/zlib_encoder.rb
110
+ - lib/codify/model_adapters/abstract_adapter.rb
111
+ - lib/codify/model_adapters/active_record_adapter.rb
112
+ - lib/codify/model_additions.rb
113
+ - lib/codify/railtie.rb
114
+ - lib/codify/version.rb
115
+ - spec/codify/base64_token_spec.rb
116
+ - spec/codify/compressed_base64_email_spec.rb
117
+ - spec/codify/compressed_email_spec.rb
118
+ - spec/codify/compressed_legacy_email_spec.rb
119
+ - spec/spec_helper.rb
120
+ homepage: https://github.com/ronalchn/codify
121
+ licenses: []
122
+ post_install_message:
123
+ rdoc_options: []
124
+ require_paths:
125
+ - lib
126
+ required_ruby_version: !ruby/object:Gem::Requirement
127
+ none: false
128
+ requirements:
129
+ - - ! '>='
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ segments:
133
+ - 0
134
+ hash: -4121720183415188968
135
+ required_rubygems_version: !ruby/object:Gem::Requirement
136
+ none: false
137
+ requirements:
138
+ - - ! '>='
139
+ - !ruby/object:Gem::Version
140
+ version: '0'
141
+ segments:
142
+ - 0
143
+ hash: -4121720183415188968
144
+ requirements: []
145
+ rubyforge_project:
146
+ rubygems_version: 1.8.17
147
+ signing_key:
148
+ specification_version: 3
149
+ summary: Automatically encodes any desired text attributes for saving to database,
150
+ and unencodes when retrieving the field. Includes encoding for compression, encryption
151
+ and error checking.
152
+ test_files:
153
+ - spec/codify/base64_token_spec.rb
154
+ - spec/codify/compressed_base64_email_spec.rb
155
+ - spec/codify/compressed_email_spec.rb
156
+ - spec/codify/compressed_legacy_email_spec.rb
157
+ - spec/spec_helper.rb