simple_restricted_attributes 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 [name of plugin creator]
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 ADDED
@@ -0,0 +1,260 @@
1
+ SimpleRestrictedAttributes
2
+ ====================
3
+
4
+ This simple_restricted_attributes plugin provides the capabilities to restrict attributes(fields)
5
+ of db table's while add or update a record. It validate your attributes values before
6
+ your validation stuff.
7
+
8
+ Features
9
+ ========
10
+
11
+ - Provides four different ways of restriction on fields (i.e read_only, create_only, update_only and hidden)
12
+ - Restrict to add/modify values of particular attributes at model level while creating/updating a record.
13
+ - Restrict functionality perform at before validation.
14
+ - Able to set restriction on instance varibles also.
15
+
16
+
17
+
18
+
19
+ *NOTE: You can try its more featured version(i.e restricted_attributes plugin) ONLY if you are using declarative_authorization plugin/gem. Find more information about that plugin on following link
20
+ (More Info - https://github.com/gkathare/restricted_attributes)
21
+
22
+
23
+
24
+
25
+
26
+ Method
27
+ ======
28
+ has_restricted_attributes(options = {})
29
+
30
+ This method accepts the options in a hash:
31
+
32
+ 1 :read_only # In this you can add attributes to restrict from add/update the value.
33
+ # Access attributes values: can read, But can't add or modify
34
+ # Format for single attribute -
35
+ # :read_only => :name or :read_only => "name"
36
+ # Format for array of attributes -
37
+ # :read_only => [:name, :bio] or :read_only => ["name", "bio"]
38
+
39
+ 2 :create_only # In this you can add attributes to restrict from update the value.
40
+ # Access attributes values: can read and add, But can't modify.
41
+ # Format for single attribute -
42
+ # :create_only => :name or :create_only => "name"
43
+ # Format for array of attributes -
44
+ # :create_only => [:name, :bio] or :create_only => ["name", "bio"]
45
+
46
+ 3 :update_only # In this you can add attributes to restrict from add the value.
47
+ # Access attributes values: can read and modify, But can't add.
48
+ # Format for single attribute -
49
+ # :update_only => :name or :update_only => "name"
50
+ # Format for array of attributes -
51
+ # :update_only => [:name, :bio] or :update_only => ["name", "bio"]
52
+
53
+ 4 :hidden_only # In this you can add attributes to restrict from add/update the value.
54
+ # Mainly used with 'is_restricted?()' helper Method & instance Method to
55
+ # check has a read access or not.
56
+ # Access attributes values: can read, But can't add or modify.
57
+ # Format for single attribute -
58
+ # :hidden_only => :name or :hidden_only => "name"
59
+ # Format for array of attributes -
60
+ # :hidden_only => [:name, :bio] or :hidden_only => ["name", "bio"]
61
+
62
+ 5 :read_only_message # validation message for read_only attributes
63
+ # Format - :read_only_message => "blah blah" (string type)
64
+ # Default message - "is a read only attribute."
65
+
66
+ 6 :create_only_message # validation message for create_only attributes
67
+ # Format - :create_only_message => "blah blah" (string type)
68
+ # Default message - "can't update, its permitted to create only."
69
+
70
+ 7 :update_only_message # validation message for update_only attributes
71
+ # Format - :update_only_message => "blah blah" (string type)
72
+ # Default message - "can't add, its permitted to update only."
73
+
74
+ 8 :hidden_only_message # validation message for hidden_only attributes
75
+ # Format - :hidden_only_message => "blah blah" (string type)
76
+ # Default message - "is a hidden attribute."
77
+
78
+
79
+
80
+ ======================================================================================================================
81
+ ------------------------------------------ Examples Set 1 ------------------------------------------------------------
82
+
83
+
84
+ # Example 1 Simple one
85
+ ================================================================
86
+
87
+ class Post < ActiveRecord::Base
88
+ has_restricted_attributes :read_only => [:status],
89
+ :create_only => [:title, :publish],
90
+ :update_only => [:tags],
91
+ :hidden_only => [:activated],
92
+ :read_only_message => "is a read only attribute",
93
+ :create_only_message => "can't update, its permitted to create only.",
94
+ :update_only_message => "can't add, its permitted to update only."
95
+ end
96
+
97
+
98
+
99
+ So, the restricted attributes will be as shown in following table.
100
+
101
+ #Post Model :
102
+
103
+ |-----------|-------------------------------------------------------------|
104
+ | |( Read/Hidden Only ) | ( Create Only ) | (Update Only ) |
105
+ | | :status /:activated | :title, :publish | :tags |
106
+ | |-------------------------------------------------------------|
107
+ | Can -> | Create | Update | Create | Update | Create | Update |
108
+ |-----------|-----------|---------|-------------------|-------------------|
109
+ | Any | | | | | | |
110
+ | User | NO | NO | YES | NO | NO | YES |
111
+ | | | | | | | |
112
+ ---------------------------------------------------------------------------
113
+
114
+ Console Output :
115
+ ---------------
116
+
117
+ >> post = Post.new(:status => true, :title => "New Title", :tags => "new, topic")
118
+ >> post.save
119
+ => false
120
+
121
+ >> post.errors
122
+ => #<OrderedHash {:status => ["is a read only attribute"], :tags=>["can't add, its permitted to update only."]}>
123
+
124
+ # for hidden attributes
125
+ >> post = Post.new(:activated => true)
126
+ >> post.save
127
+ => false
128
+
129
+ >> post.errors
130
+ => #<OrderedHash {:status => ["is a hidden attribute"]}>
131
+ OR
132
+ >> post.is_restricted?(:read, :activated) # To check :activated field is restricted to read.
133
+ => true
134
+
135
+
136
+ --------------------------------------------- End Examples Set 1 -----------------------------------------------------
137
+ ======================================================================================================================
138
+
139
+
140
+
141
+
142
+
143
+ Helper Method & Instance Method ( For View & Controller files )
144
+ ===============================================================
145
+
146
+
147
+ 1 Helper Method `is_restricted?()` :
148
+ ------------------------------------
149
+
150
+ Syntax:
151
+ -------------------------------------------------
152
+ | is_restricted?(Klass, action, field) |
153
+ -------------------------------------------------
154
+
155
+ This method accepts 3 arguments :
156
+
157
+ 1 Klass # This is a mandatory & first argument of this method.
158
+ # Should be valid class (i.e Model Name), no String.
159
+ # Should be in constantize format
160
+ # Ex : User , Post, Comment
161
+
162
+ 2 action # This is a mandatory & second argument of this method.
163
+ # Valid actions : "create" or "update" or "read".
164
+ # Should be either in symbol or in string format
165
+ # Ex : :create or :update or :read or "create" or "update" or "read"
166
+
167
+ 3 field # This is a mandatory & third argument of this method.
168
+ # Should be valid attributes/field of that model or related db table.
169
+ # Should be either in symbol or in string format
170
+ # Ex : :title or "title"
171
+
172
+
173
+
174
+ 2 Instance Method `is_restricted?()` :
175
+ --------------------------------------
176
+
177
+ Syntax:
178
+ ----------------------------------------------
179
+ | object.is_restricted?(action, field) |
180
+ ----------------------------------------------
181
+
182
+ This method accepts 2 arguments :
183
+
184
+ 1 action # This is a mandatory & first argument of this method.
185
+ # Valid actions : "create" or "update" or "read".
186
+ # Should be either in symbol or in string format
187
+ # Ex : :create or :update or :read or "create" or "update" or "read"
188
+
189
+ 2 field # This is a mandatory & second argument of this method.
190
+ # Should be valid attributes/field of that model or related db table.
191
+ # Should be either in symbol or in string format
192
+ # Ex : :title or "title"
193
+
194
+
195
+
196
+
197
+ ======================================================================================================================
198
+ ------------------------------------------ Examples Set 2 ------------------------------------------------------------
199
+
200
+
201
+
202
+ # Example 1 ( Use of Helper Method )
203
+ ====================================
204
+
205
+ # /models/post.rb
206
+ class Post < ActiveRecord::Base
207
+ has_restricted_attributes :read_only => [:active],
208
+ :create_only => [:title],
209
+ :update_only => [:abuse],
210
+ :read_only_message => "is a read only attribute"
211
+ end
212
+
213
+ So for this post class we can check its particular field is restricted or not.
214
+ (You can use this method in controller, view and helper file.)
215
+
216
+ ---------------------------------------------------
217
+ | is_restricted?(Post, :update, :title) |
218
+ ---------------------------------------------------
219
+
220
+ - return true(:title is restricted)
221
+
222
+
223
+
224
+
225
+ # Example 2 ( Use of Instance Method )
226
+ =======================================
227
+
228
+ # /models/post.rb
229
+ class Post < ActiveRecord::Base
230
+ has_restricted_attributes :read_only => [:active],
231
+ :create_only => [:title],
232
+ :update_only => [:abuse],
233
+ :read_only_message => "is a read only attribute"
234
+ end
235
+
236
+ So for this post class we can check its particular field is restricted or not.
237
+
238
+ -----------------------------------------------------
239
+ | post = Post.find(params[:id]) |
240
+ | is_restricted?(:update, :title) |
241
+ -----------------------------------------------------
242
+
243
+ - return true(:title is restricted)
244
+
245
+
246
+
247
+
248
+ --------------------------------------------- End Examples Set 2 -----------------------------------------------------
249
+ ======================================================================================================================
250
+
251
+
252
+
253
+
254
+ ===========================================================================
255
+ Easiest way to contact me(Ganesh Kathare):
256
+ My email - kathare[dot]ganesh[at]gmail[dot]com (kathare.ganesh@gmail.com)
257
+ ===========================================================================
258
+
259
+ Copyright (c) 2011 Ganesh Kathare, Navi Mumbai MH, India. released under the MIT license
260
+
@@ -0,0 +1,37 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/clean'
4
+ require 'rake/gempackagetask'
5
+ require 'rake/rdoctask'
6
+ require 'rake/testtask'
7
+
8
+
9
+ PKG_FILES = FileList[
10
+ '[a-zA-Z]*',
11
+ 'lib/**/*',
12
+ 'test/**/*'
13
+ ]
14
+
15
+ spec = Gem::Specification.new do |s|
16
+ s.name = "simple_restricted_attributes"
17
+ s.version = "1.0.0"
18
+ s.author = "Ganesh Kathare"
19
+ s.email = "kathare.ganesh@gmail.com"
20
+ s.homepage = "https://github.com/gkathare"
21
+ s.platform = Gem::Platform::RUBY
22
+ s.summary = "Sharing simple_restricted_attributes"
23
+ s.files = PKG_FILES.to_a
24
+ s.require_path = "lib"
25
+ s.has_rdoc = false
26
+ s.extra_rdoc_files = ["README"]
27
+ s.description = <<EOF
28
+ This simple_restricted_attributes plugin/gem provides the capabilities to restrict attributes(fields)
29
+ of db table's while add or update a record. It validate your attributes values before
30
+ your validation stuff.
31
+ EOF
32
+ end
33
+
34
+ Rake::GemPackageTask.new(spec) do |pkg|
35
+ pkg.need_zip = true
36
+ pkg.need_tar = true
37
+ end
data/init.rb ADDED
@@ -0,0 +1,3 @@
1
+ # Include hook code here
2
+ $:.unshift "#{File.dirname(__FILE__)}/lib"
3
+ require 'simple_restricted_attributes'
@@ -0,0 +1,104 @@
1
+ module RestrictedAttrib
2
+
3
+ ## Class Methods
4
+ module ClassMethods
5
+ def self.extended(base)
6
+ base.before_validation :check_for_restricted_values
7
+ end
8
+ end
9
+
10
+ ## Instance Methods
11
+ module InstanceMethods
12
+ # check the changed attributes of a class are restricted or not.
13
+ def check_for_restricted_values
14
+
15
+ restrict_read_only = self.read_only
16
+ restrict_create_only = self.create_only
17
+ restrict_update_only = self.update_only
18
+ restrict_hidden_only = self.hidden_only
19
+
20
+ # check for read only attributes
21
+ unless restrict_read_only.blank?
22
+ restrict_read_only.each do |ro|
23
+ if self.changed.include?(ro) || !eval("self.instance_variable_get :@#{ro}").blank?
24
+ self.errors.add(ro.humanize, self.read_only_message)
25
+ end
26
+ end
27
+ end
28
+
29
+ # check for create only attributes
30
+ if !restrict_create_only.blank? && !self.new_record?
31
+ restrict_create_only.each do |co|
32
+ if self.changed.include?(co) || !eval("self.instance_variable_get :@#{co}").blank?
33
+ self.errors.add(co.humanize, self.create_only_message)
34
+ end
35
+ end
36
+ end
37
+
38
+ # check for update only attributes
39
+ if !restrict_update_only.blank? && self.new_record?
40
+ restrict_update_only.each do |uo|
41
+ if self.changed.include?(uo) || !eval("self.instance_variable_get :@#{uo}").blank?
42
+ self.errors.add(uo.humanize, self.update_only_message)
43
+ end
44
+ end
45
+ end
46
+
47
+ # check for hidden only attributes
48
+ if !restrict_hidden_only.blank?
49
+ restrict_hidden_only.each do |ho|
50
+ if self.changed.include?(ho) || !eval("self.instance_variable_get :@#{ho}").blank?
51
+ self.errors.add(ho.humanize, self.hidden_only_message)
52
+ end
53
+ end
54
+ end
55
+
56
+ # will return validation result
57
+ return false unless self.errors.blank?
58
+ end
59
+
60
+ def is_restricted?(action, field, user = nil)
61
+ action = action.to_s
62
+ field = field.to_s
63
+ klass = self.class
64
+ klass_object = self
65
+
66
+ unless klass_object.methods.include?("read_only")
67
+ raise NoMethodError, "undefined method `is_restricted?` for #{klass} model. You need to add `has_restricted_method` method in #{klass} model."
68
+ end
69
+
70
+ if action.nil? || !['create', 'update', 'read'].include?(action)
71
+ raise ArgumentError, "Invalid action - (#{action}), Pass valid action - :read or :create or :update or 'read' or 'create' or 'update'"
72
+ end
73
+
74
+ klass_attributes = klass_object.attributes.keys
75
+ if field.nil? || (!klass_attributes.include?(field) && !klass_object.methods.include?("#{field}="))
76
+ raise ActiveRecord::UnknownAttributeError, "#{klass}: unknown attribute(field): #{field}"
77
+ end
78
+
79
+ restrict_read_only = self.read_only
80
+ restrict_create_only = self.create_only
81
+ restrict_update_only = self.update_only
82
+ restrict_hidden_only = self.hidden_only
83
+
84
+ if action == "create" || action == "update" || action == "read"
85
+ return true if !restrict_hidden_only.blank? && restrict_hidden_only.include?(field)
86
+ end
87
+
88
+ if action == "create" || action == "update"
89
+ return true if !restrict_read_only.blank? && restrict_read_only.include?(field)
90
+ end
91
+
92
+ if action == "create"
93
+ return true if !restrict_update_only.blank? && restrict_update_only.include?(field)
94
+ end
95
+
96
+ if action == "update"
97
+ return true if !restrict_create_only.blank? && restrict_create_only.include?(field)
98
+ end
99
+ return false
100
+ end
101
+
102
+ end
103
+ end
104
+
@@ -0,0 +1,120 @@
1
+ require "restricted/restricted_attrib"
2
+
3
+ module SimpleRestrictedAttributes
4
+
5
+ module Restricted
6
+
7
+ def has_restricted_attributes(options = {})
8
+ cattr_accessor :read_only, :create_only, :update_only, :hidden_only
9
+ cattr_accessor :read_only_message, :create_only_message, :update_only_message, :hidden_only_message
10
+
11
+ # set the read only attributes of a class
12
+ if options[:read_only]
13
+ only_read = []
14
+ if options[:read_only].is_a?(Array)
15
+ only_read = options[:read_only].collect {|r| r.to_s }
16
+ else
17
+ only_read << options[:read_only].to_s
18
+ end
19
+ self.read_only = only_read
20
+ end
21
+
22
+ # set the create only attributes of a class
23
+ if options[:create_only]
24
+ only_create = []
25
+ if options[:create_only].is_a?(Array)
26
+ only_create = options[:create_only].collect {|c| c.to_s }
27
+ else
28
+ only_create << options[:create_only].to_s
29
+ end
30
+ self.create_only = only_create
31
+ end
32
+
33
+ # set the create only attributes of a class
34
+ if options[:update_only]
35
+ only_update = []
36
+ if options[:update_only].is_a?(Array)
37
+ only_update = options[:update_only].collect {|u| u.to_s }
38
+ else
39
+ only_update << options[:update_only].to_s
40
+ end
41
+ self.update_only = only_update
42
+ end
43
+
44
+ # set the hidden only attributes of a class
45
+ if options[:hidden_only]
46
+ only_hidden = []
47
+ if options[:hidden_only].is_a?(Array)
48
+ only_hidden = options[:hidden_only].collect {|u| u.to_s }
49
+ else
50
+ only_hidden << options[:hidden_only].to_s
51
+ end
52
+ self.hidden_only = only_hidden
53
+ end
54
+
55
+ # Default validation messages
56
+ ro_msg = "is a read only attribute."
57
+ co_msg = "can't update, its permitted to create only."
58
+ uo_msg = "can't add, its permitted to update only."
59
+ ho_msg = "is a hidden attribute."
60
+
61
+ # assign validation messages to restricted attributes
62
+ self.read_only_message = options[:read_only_message] ? options[:read_only_message].to_s : ro_msg
63
+ self.create_only_message = options[:create_only_message] ? options[:create_only_message].to_s : co_msg
64
+ self.update_only_message = options[:update_only_message] ? options[:update_only_message].to_s : uo_msg
65
+ self.hidden_only_message = options[:hidden_only_message] ? options[:hidden_only_message].to_s : ho_msg
66
+
67
+ extend RestrictedAttrib::ClassMethods
68
+ include RestrictedAttrib::InstanceMethods
69
+ end
70
+ end
71
+
72
+ module RestrictedHelpers
73
+ def is_restricted?(klass, action, field, user = nil)
74
+ action = action.to_s
75
+ field = field.to_s
76
+ raise ArgumentError, "Must pass valid class" if klass.nil? || !klass.is_a?(Class)
77
+
78
+ klass_object = klass.new
79
+
80
+ unless klass_object.methods.include?("read_only")
81
+ raise NoMethodError, "undefined method `is_restricted?` for #{klass} model. You need to add `has_restricted_attributes` method in #{klass} model."
82
+ end
83
+
84
+ if action.nil? || !['create', 'update', 'read'].include?(action)
85
+ raise ArgumentError, "Invalid action - (#{action}), Pass valid action - :read or :create or :update or 'read' or 'create' or 'update'"
86
+ end
87
+
88
+ klass_attributes = klass_object.attributes.keys
89
+ if field.nil? || !klass_attributes.include?(field)
90
+ raise ActiveRecord::UnknownAttributeError, "#{klass}: unknown attribute(field): #{field}"
91
+ end
92
+
93
+ restrict_read_only = klass_object.read_only
94
+ restrict_create_only = klass_object.create_only
95
+ restrict_update_only = klass_object.update_only
96
+ restrict_hidden_only = klass_object.hidden_only
97
+
98
+ if action == "create" || action == "update" || action == "read"
99
+ return true if !restrict_hidden_only.blank? && restrict_hidden_only.include?(field)
100
+ end
101
+
102
+ if action == "create" || action == "update"
103
+ return true if !restrict_read_only.blank? && restrict_read_only.include?(field)
104
+ end
105
+
106
+ if action == "create"
107
+ return true if !restrict_update_only.blank? && restrict_update_only.include?(field)
108
+ end
109
+
110
+ if action == "update"
111
+ return true if !restrict_create_only.blank? && restrict_create_only.include?(field)
112
+ end
113
+ return false
114
+ end
115
+ end
116
+ end
117
+
118
+ ActiveRecord::Base.send(:extend, SimpleRestrictedAttributes::Restricted)
119
+ ActionView::Base.send(:include, SimpleRestrictedAttributes::RestrictedHelpers)
120
+ ActionController::Base.send(:include, SimpleRestrictedAttributes::RestrictedHelpers)
@@ -0,0 +1,8 @@
1
+ require 'test_helper'
2
+
3
+ class SimpleRestrictedAttributesTest < ActiveSupport::TestCase
4
+ # Replace this with your real tests.
5
+ test "the truth" do
6
+ assert true
7
+ end
8
+ end
@@ -0,0 +1,3 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'active_support'
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_restricted_attributes
3
+ version: !ruby/object:Gem::Version
4
+ prerelease:
5
+ version: 1.0.0
6
+ platform: ruby
7
+ authors:
8
+ - Ganesh Kathare
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2011-07-21 00:00:00 +05:30
14
+ default_executable:
15
+ dependencies: []
16
+
17
+ description: " This simple_restricted_attributes plugin/gem provides the capabilities to restrict attributes(fields) \n of db table's while add or update a record. It validate your attributes values before\n your validation stuff.\n"
18
+ email: kathare.ganesh@gmail.com
19
+ executables: []
20
+
21
+ extensions: []
22
+
23
+ extra_rdoc_files:
24
+ - README
25
+ files:
26
+ - init.rb
27
+ - MIT-LICENSE
28
+ - Rakefile
29
+ - README
30
+ - lib/simple_restricted_attributes.rb
31
+ - lib/restricted/restricted_attrib.rb
32
+ - test/simple_restricted_attributes_test.rb
33
+ - test/test_helper.rb
34
+ has_rdoc: true
35
+ homepage: https://github.com/gkathare
36
+ licenses: []
37
+
38
+ post_install_message:
39
+ rdoc_options: []
40
+
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ none: false
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: "0"
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: "0"
55
+ requirements: []
56
+
57
+ rubyforge_project:
58
+ rubygems_version: 1.5.1
59
+ signing_key:
60
+ specification_version: 3
61
+ summary: Sharing simple_restricted_attributes
62
+ test_files: []
63
+