dynamic_attributes 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,21 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+
21
+ ## PROJECT::SPECIFIC
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Reinier de Lange
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,75 @@
1
+ = dynamic_attributes
2
+
3
+ dynamic_attributes is a gem that lets you dynamically specify attributes on ActiveRecord models, which will be serialized and
4
+ deserialized to a given text column.
5
+
6
+ == Requirements
7
+
8
+ * Rails 2.x
9
+
10
+ == Installation
11
+
12
+ * config.gem 'dynamic_attributes', sudo rake gems:install
13
+ * gem install dynamic_attributes
14
+
15
+ == Usage
16
+
17
+ To add dynamic_attributes to an AR model, take the following steps:
18
+
19
+ * Create a migration to add a column to serialize the dynamic attributes to:
20
+
21
+ class AddDynamicAttributesToDynamicModels < ActiveRecord::Migration
22
+ def self.up
23
+ add_column :dynamic_models, :dynamic_attributes, :text
24
+ end
25
+
26
+ def self.down
27
+ remove_column :dynamic_models, :dynamic_attributes
28
+ end
29
+ end
30
+
31
+ * Add dynamic_attributes to your AR model:
32
+
33
+ class DynamicModel < ActiveRecord::Base
34
+ has_dynamic_attributes
35
+ end
36
+
37
+ * Now you can add dynamic attributes in several ways. Examples:
38
+
39
+ - New: DynamicModel.new(:title => 'Hello', :field_summary => 'This is a dynamic attribute')
40
+ - Create: DynamicModel.create(:title => 'Hello', :field_summary => 'This is a dynamic attribute')
41
+ - Update:
42
+ * dynamic_model.update_atribute(:field_summary, 'This is a dynamic attribute')
43
+ * dynamic_model.update_atributes(:field_summary => 'This is a dynamic attribute', :description => 'Testing')
44
+ - Set manually: dynamic_model.field_summary = 'This is a dynamic attribute'
45
+
46
+ == Options
47
+
48
+ The has_dynamic_attribute call takes three different options:
49
+
50
+ * :dynamic_attribute_field
51
+ - Defines the database column to serialize to.
52
+ * :dynamic_attribute_prefix
53
+ - Defines the prefix that a dynamic attribute should have. All attribute assignments that start with this prefix will become dynamic attributes. Note that it's not recommended to set this prefix to the empty string; as every method call that falls through to method_missing will become a dynamic attribute.
54
+ * :destroy_dynamic_attribute_for_nil
55
+ - When set to true, the module will remove a dynamic attribute when its value is set to nil. Defaults to false, causing the module to store a dynamic attribute even if its value is nil.
56
+
57
+ By default, the has_dynamic_attributes call without options equals to calling:
58
+
59
+ has_dynamic_attributes :dynamic_attribute_field => :dynamic_attributes, :dynamic_attribute_prefix => 'field_', :destroy_dynamic_attribute_for_nil => false
60
+
61
+ Take a look at the code Rdoc for more information!
62
+
63
+ == Note on Patches/Pull Requests
64
+
65
+ * Fork the project.
66
+ * Make your feature addition or bug fix.
67
+ * Add tests for it. This is important so I don't break it in a
68
+ future version unintentionally.
69
+ * Commit, do not mess with rakefile, version, or history.
70
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
71
+ * Send me a pull request. Bonus points for topic branches.
72
+
73
+ == Copyright
74
+
75
+ Copyright (c) 2010 Reinier de Lange. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,70 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "dynamic_attributes"
8
+ gem.summary = %Q{Dynamic attributes is a gem that lets you dynamically specify attributes on ActiveRecord models, which will be serialized and
9
+ deserialized to a given text column.}
10
+ gem.description = %Q{Dynamic attributes is a gem that lets you dynamically specify attributes on ActiveRecord models, which will be serialized and
11
+ deserialized to a given text column. Dynamic attributes can be defined by simply setting an attribute or by passing them on create or update.}
12
+ gem.email = "r.j.delange@nedforce.nl"
13
+ gem.homepage = "http://github.com/moiristo/dynamic_attributes"
14
+ gem.authors = ["Reinier de Lange"]
15
+ gem.files = [
16
+ "init.rb",
17
+ ".document",
18
+ ".gitignore",
19
+ "LICENSE",
20
+ "README.rdoc",
21
+ "Rakefile",
22
+ "VERSION",
23
+ "lib/dynamic_attributes.rb"
24
+ ]
25
+ gem.test_files = [
26
+ "test/helper.rb",
27
+ "test/test_dynamic_attributes.rb",
28
+ "test/database.yml",
29
+ "test/schema.rb"
30
+ ]
31
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
32
+ end
33
+ Jeweler::GemcutterTasks.new
34
+ rescue LoadError
35
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
36
+ end
37
+
38
+ require 'rake/testtask'
39
+ Rake::TestTask.new(:test) do |test|
40
+ test.libs << 'lib' << 'test'
41
+ test.pattern = 'test/**/test_*.rb'
42
+ test.verbose = true
43
+ end
44
+
45
+ begin
46
+ require 'rcov/rcovtask'
47
+ Rcov::RcovTask.new do |test|
48
+ test.libs << 'test'
49
+ test.pattern = 'test/**/test_*.rb'
50
+ test.verbose = true
51
+ end
52
+ rescue LoadError
53
+ task :rcov do
54
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
55
+ end
56
+ end
57
+
58
+ task :test => :check_dependencies
59
+
60
+ task :default => :test
61
+
62
+ require 'rake/rdoctask'
63
+ Rake::RDocTask.new do |rdoc|
64
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
65
+
66
+ rdoc.rdoc_dir = 'rdoc'
67
+ rdoc.title = "dynamic_attributes #{version}"
68
+ rdoc.rdoc_files.include('README*')
69
+ rdoc.rdoc_files.include('lib/**/*.rb')
70
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.0
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require 'dynamic_attributes'
@@ -0,0 +1,118 @@
1
+
2
+ # Adds the has_dynamic_attributes method in ActiveRecord::Base, which can be used to configure the module.
3
+ class << ActiveRecord::Base
4
+
5
+ # Method to call in AR classes in order to be able to define dynamic attributes. The following options can be defined:
6
+ #
7
+ # * :dynamic_attribute_field - Defines the attribute to which all dynamic attributes will be serialized. Default: :dynamic_attributes.
8
+ # * :dynamic_attribute_prefix - Defines the prefix that a dynamic attribute should have. All assignments that start with this prefix will become
9
+ # dynamic attributes. Note that it's not recommended to set this prefix to the empty string; as every method call that falls through to method_missing
10
+ # will become a dynamic attribute. Default: 'field_'
11
+ # * :destroy_dynamic_attribute_for_nil - When set to true, the module will remove a dynamic attribute when its value is set to nil. Defaults to false, causing
12
+ # the module to store a dynamic attribute even if its value is nil.
13
+ #
14
+ def has_dynamic_attributes(options = { :dynamic_attribute_field => :dynamic_attributes, :dynamic_attribute_prefix => 'field_', :destroy_dynamic_attribute_for_nil => false})
15
+ cattr_accessor :dynamic_attribute_field
16
+ self.dynamic_attribute_field = options[:dynamic_attribute_field] || :dynamic_attributes
17
+ cattr_accessor :dynamic_attribute_prefix
18
+ self.dynamic_attribute_prefix = options[:dynamic_attribute_prefix] || 'field_'
19
+ cattr_accessor :destroy_dynamic_attribute_for_nil
20
+ self.destroy_dynamic_attribute_for_nil = options[:destroy_dynamic_attribute_for_nil] || false
21
+
22
+ include DynamicAttributes
23
+ end
24
+ end
25
+
26
+ # The DynamicAttributes module handles all dynamic attributes.
27
+ module DynamicAttributes
28
+
29
+ # On saving an AR record, the attributes to be persisted are re-evaluated and written to the serialization field.
30
+ def before_save
31
+ new_dynamic_attributes = {}
32
+ self.persisting_dynamic_attributes.uniq.each do |dynamic_attribute|
33
+ value = send(dynamic_attribute)
34
+ if value.nil? and destroy_dynamic_attribute_for_nil
35
+ self.persisting_dynamic_attributes.delete(dynamic_attribute)
36
+ singleton_class.send(:remove_method, dynamic_attribute + '=')
37
+ else
38
+ new_dynamic_attributes[dynamic_attribute] = value
39
+ end
40
+ end
41
+ write_attribute(self.dynamic_attribute_field, new_dynamic_attributes)
42
+ end
43
+
44
+ # After find, populate the dynamic attributes and create accessors
45
+ def after_find
46
+ (read_attribute(self.dynamic_attribute_field) || {}).each {|att, value| set_dynamic_attribute(att, value); self.destroy_dynamic_attribute_for_nil = false if value.nil? }
47
+ end
48
+
49
+ # Creates an accessor when a non-existing setter with the configured dynamic attribute prefix is detected. Calls super otherwise.
50
+ def method_missing(method, *arguments, &block)
51
+ (method.to_s =~ /#{self.dynamic_attribute_prefix}(.+)=/) ? set_dynamic_attribute(self.dynamic_attribute_prefix + $1, *arguments.first) : super
52
+ end
53
+
54
+ # Overrides the initializer to take dynamic attributes into account
55
+ def initialize(attributes = nil)
56
+ dynamic_attributes = {}
57
+ attributes.each{|att,value| dynamic_attributes[att] = value if att.to_s.starts_with?(self.dynamic_attribute_prefix) }
58
+ super(attributes.except(*dynamic_attributes.keys))
59
+ set_dynamic_attributes(dynamic_attributes)
60
+ end
61
+
62
+ # Overrides update_attributes to take dynamic attributes into account
63
+ def update_attributes(attributes)
64
+ set_dynamic_attributes(attributes)
65
+ super(attributes)
66
+ end
67
+
68
+ # Returns the dynamic attributes that will be persisted to the serialization column. This array can
69
+ # be altered to force dynamic attributes to not be saved in the database or to persist other attributes, but
70
+ # it is recommended to not change it at all.
71
+ def persisting_dynamic_attributes
72
+ @persisting_dynamic_attributes ||= []
73
+ end
74
+
75
+ # Ensures the configured dynamic attribute field is serialized by AR.
76
+ def self.included object
77
+ object.serialize object.dynamic_attribute_field
78
+ end
79
+
80
+ private
81
+
82
+ # Method that is called when a dynamic attribute is added to this model. It adds this attribute to the list
83
+ # of attributes that will be persisited, creates an accessor and sets the attribute value. To reflect that the
84
+ # attribute has been added, the serialization attribute will also be updated.
85
+ def set_dynamic_attribute(att, value)
86
+ att = att.to_s
87
+ persisting_dynamic_attributes << att
88
+ singleton_class.send(:attr_accessor, att)
89
+ send(att + '=', value)
90
+ update_dynamic_attribute(att, value)
91
+ end
92
+
93
+ # Called on object initialization or when calling update_attributes to convert passed dynamic attributes
94
+ # into attributes that will be persisted by calling set_dynamic_attribute if it does not exist already.
95
+ # The serialization column will also be updated and the detected dynamic attributes are removed from the passed
96
+ # attributes hash.
97
+ def set_dynamic_attributes(attributes)
98
+ return if attributes.nil?
99
+
100
+ attributes.each do |att, value|
101
+ if att.to_s.starts_with?(self.dynamic_attribute_prefix)
102
+ attributes.delete(att)
103
+ unless respond_to?(att.to_s + '=')
104
+ set_dynamic_attribute(att, value)
105
+ else
106
+ send(att.to_s + '=', value);
107
+ update_dynamic_attribute(att, value)
108
+ end
109
+ end
110
+ end
111
+ end
112
+
113
+ # Updates the serialization column with a new attribute and value.
114
+ def update_dynamic_attribute(attribute, value)
115
+ write_attribute(self.dynamic_attribute_field.to_s, (read_attribute(self.dynamic_attribute_field.to_s) || {}).merge(attribute.to_s => value))
116
+ end
117
+
118
+ end
data/test/database.yml ADDED
@@ -0,0 +1,6 @@
1
+ sqlite:
2
+ adapter: sqlite
3
+ database: ":memory:"
4
+ sqlite3:
5
+ adapter: sqlite3
6
+ database: ":memory:"
data/test/helper.rb ADDED
@@ -0,0 +1,39 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+
4
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
5
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
6
+
7
+ gem "activerecord"
8
+ require 'active_record'
9
+ require 'dynamic_attributes'
10
+ require 'pp'
11
+
12
+ class DynamicModel < ActiveRecord::Base
13
+ has_dynamic_attributes :dynamic_attribute_field => :dynamic_attributes, :dynamic_attribute_prefix => 'field_', :destroy_dynamic_attribute_for_nil => false
14
+ end
15
+
16
+ def load_schema
17
+ config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
18
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
19
+ db_adapter = ENV['DB']
20
+ # no db passed, try one of these fine config-free DBs before bombing.
21
+ db_adapter ||= begin
22
+ require 'rubygems'
23
+ require 'sqlite'
24
+ 'sqlite'
25
+ rescue MissingSourceFile
26
+ begin
27
+ require 'sqlite3'
28
+ 'sqlite3'
29
+ rescue MissingSourceFile
30
+ end
31
+ end
32
+
33
+ if db_adapter.nil?
34
+ raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
35
+ end
36
+ ActiveRecord::Base.establish_connection(config[db_adapter])
37
+ load(File.dirname(__FILE__) + "/schema.rb")
38
+ require File.dirname(__FILE__) + '/../init.rb'
39
+ end
data/test/schema.rb ADDED
@@ -0,0 +1,7 @@
1
+ ActiveRecord::Schema.define(:version => 0) do
2
+ create_table :dynamic_models, :force => true do |t|
3
+ t.string :title
4
+ t.text :dynamic_attributes
5
+ t.text :extra
6
+ end
7
+ end
@@ -0,0 +1,83 @@
1
+ require 'helper'
2
+
3
+ class TestDynamicAttributes < Test::Unit::TestCase
4
+ load_schema
5
+
6
+ def setup
7
+ DynamicModel.dynamic_attribute_field = :dynamic_attributes
8
+ DynamicModel.dynamic_attribute_prefix = 'field_'
9
+ DynamicModel.destroy_dynamic_attribute_for_nil = false
10
+
11
+ @dynamic_model = DynamicModel.create(:title => "A dynamic model")
12
+ end
13
+
14
+ def test_should_persist_nothing_by_default
15
+ assert_equal [], @dynamic_model.persisting_dynamic_attributes
16
+ end
17
+
18
+ def test_should_create_manual_dynamic_attribute
19
+ @dynamic_model.field_test = 'hello'
20
+ assert_equal 'hello', @dynamic_model.field_test
21
+ assert @dynamic_model.persisting_dynamic_attributes.include?('field_test')
22
+ assert @dynamic_model.dynamic_attributes.keys.include?('field_test')
23
+ end
24
+
25
+ def test_should_create_dynamic_attributes_for_hash
26
+ assert dynamic_model = DynamicModel.create(:title => 'Title', :field_test1 => 'Hello', :field_test2 => 'World')
27
+ assert dynamic_model.persisting_dynamic_attributes.include?('field_test1')
28
+ assert dynamic_model.persisting_dynamic_attributes.include?('field_test2')
29
+ assert_equal 'Hello', dynamic_model.field_test1
30
+ assert_equal 'World', dynamic_model.field_test2
31
+ end
32
+
33
+ def test_should_update_attributes
34
+ @dynamic_model.update_attributes(:title => 'Title', :field_test1 => 'Hello', :field_test2 => 'World')
35
+ assert @dynamic_model.persisting_dynamic_attributes.include?('field_test1')
36
+ assert @dynamic_model.persisting_dynamic_attributes.include?('field_test2')
37
+ assert_equal 'Hello', @dynamic_model.field_test1
38
+ assert_equal 'World', @dynamic_model.field_test2
39
+
40
+ @dynamic_model.reload
41
+ assert_equal 'Hello', @dynamic_model.field_test1
42
+ assert_equal 'World', @dynamic_model.field_test2
43
+ end
44
+
45
+ def test_should_load_dynamic_attributes_after_find
46
+ DynamicModel.update_all("dynamic_attributes = '---\nfield_test: Hi!\n'", :id => @dynamic_model.id)
47
+ dynamic_model = DynamicModel.find(@dynamic_model.id)
48
+ assert_equal 'Hi!', dynamic_model.field_test
49
+ end
50
+
51
+ def test_should_set_dynamic_attribute_to_nil_if_configured
52
+ assert @dynamic_model.update_attribute(:field_test,nil)
53
+ assert_nil @dynamic_model.field_test
54
+ assert @dynamic_model.persisting_dynamic_attributes.include?('field_test')
55
+ assert @dynamic_model.dynamic_attributes.include?('field_test')
56
+
57
+ DynamicModel.destroy_dynamic_attribute_for_nil = true
58
+ assert @dynamic_model.update_attribute(:field_test,nil)
59
+ assert !@dynamic_model.persisting_dynamic_attributes.include?('field_test')
60
+ assert !@dynamic_model.dynamic_attributes.include?('field_test')
61
+ assert !@dynamic_model.respond_to?('field_test=')
62
+ end
63
+
64
+ def test_should_allow_different_prefix
65
+ DynamicModel.dynamic_attribute_prefix = 'what_'
66
+
67
+ @dynamic_model.what_test = 'hello'
68
+ assert_equal 'hello', @dynamic_model.what_test
69
+ assert @dynamic_model.persisting_dynamic_attributes.include?('what_test')
70
+ assert @dynamic_model.dynamic_attributes.keys.include?('what_test')
71
+
72
+ assert_raises NoMethodError do
73
+ @dynamic_model.field_test = 'Fail'
74
+ end
75
+ end
76
+
77
+ def test_should_allow_different_serialization_field
78
+ DynamicModel.dynamic_attribute_field = 'extra'
79
+ @dynamic_model.update_attributes(:title => 'Title', :field_test1 => 'Hello', :field_test2 => 'World')
80
+ assert_equal({}, @dynamic_model.dynamic_attributes)
81
+ assert_equal({"field_test1"=>"Hello", "field_test2"=>"World"}, @dynamic_model.extra)
82
+ end
83
+ end
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dynamic_attributes
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 1
7
+ - 0
8
+ - 0
9
+ version: 1.0.0
10
+ platform: ruby
11
+ authors:
12
+ - Reinier de Lange
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-07-29 00:00:00 +02:00
18
+ default_executable:
19
+ dependencies: []
20
+
21
+ description: |-
22
+ Dynamic attributes is a gem that lets you dynamically specify attributes on ActiveRecord models, which will be serialized and
23
+ deserialized to a given text column. Dynamic attributes can be defined by simply setting an attribute or by passing them on create or update.
24
+ email: r.j.delange@nedforce.nl
25
+ executables: []
26
+
27
+ extensions: []
28
+
29
+ extra_rdoc_files:
30
+ - LICENSE
31
+ - README.rdoc
32
+ files:
33
+ - .document
34
+ - .gitignore
35
+ - LICENSE
36
+ - README.rdoc
37
+ - Rakefile
38
+ - VERSION
39
+ - init.rb
40
+ - lib/dynamic_attributes.rb
41
+ has_rdoc: true
42
+ homepage: http://github.com/moiristo/dynamic_attributes
43
+ licenses: []
44
+
45
+ post_install_message:
46
+ rdoc_options:
47
+ - --charset=UTF-8
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ segments:
55
+ - 0
56
+ version: "0"
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ segments:
62
+ - 0
63
+ version: "0"
64
+ requirements: []
65
+
66
+ rubyforge_project:
67
+ rubygems_version: 1.3.6
68
+ signing_key:
69
+ specification_version: 3
70
+ summary: Dynamic attributes is a gem that lets you dynamically specify attributes on ActiveRecord models, which will be serialized and deserialized to a given text column.
71
+ test_files:
72
+ - test/helper.rb
73
+ - test/test_dynamic_attributes.rb
74
+ - test/database.yml
75
+ - test/schema.rb