Module: Redmine::SafeAttributes

Included in:
Comment, Document, Issue, IssueCategory, Message, News, Project, TimeEntry, User, Version, Wiki
Defined in:
lib/redmine/safe_attributes.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



17
18
19
# File 'lib/redmine/safe_attributes.rb', line 17

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#delete_unsafe_attributes(attrs, user = User.current) ⇒ Object

Returns a hash with unsafe attributes removed from the given attrs hash

Example:

book.delete_unsafe_attributes({'title' => 'My book', 'foo' => 'bar'})
# => {'title' => 'My book'}


65
66
67
68
# File 'lib/redmine/safe_attributes.rb', line 65

def delete_unsafe_attributes(attrs, user=User.current)
  safe = safe_attribute_names(user)
  attrs.dup.delete_if {|k,v| !safe.include?(k.to_s)}
end

#safe_attribute_names(user = User.current) ⇒ Object

Returns an array that can be safely set by user or current user

Example:

book.safe_attributes # => ['title', 'pages']
book.safe_attributes(book.author) # => ['title', 'pages', 'isbn']


49
50
51
52
53
54
55
56
57
# File 'lib/redmine/safe_attributes.rb', line 49

def safe_attribute_names(user=User.current)
  names = []
  self.class.safe_attributes.collect do |attrs, options|
    if options[:if].nil? || options[:if].call(self, user)
      names += attrs.collect(&:to_s)
    end
  end
  names.uniq
end

#safe_attributes=(attrs, user = User.current) ⇒ Object

Sets attributes from attrs that are safe attrs is a Hash with string keys



72
73
74
75
# File 'lib/redmine/safe_attributes.rb', line 72

def safe_attributes=(attrs, user=User.current)
  return unless attrs.is_a?(Hash)
  self.attributes = delete_unsafe_attributes(attrs, user)
end