Module: Redmine::SafeAttributes

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

Overview

Since:

  • 1.1.0

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

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'}


75
76
77
78
# File 'lib/redmine/safe_attributes.rb', line 75

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

#safe_attribute?(attr, user = nil) ⇒ Boolean

Returns true if attr can be set by user or the current user

Returns:

  • (Boolean)

Since:

  • 1.4.0



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

def safe_attribute?(attr, user=nil)
  safe_attribute_names(user).include?(attr.to_s)
end

#safe_attribute_names(user = nil) ⇒ 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']


51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/redmine/safe_attributes.rb', line 51

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

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

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



82
83
84
85
# File 'lib/redmine/safe_attributes.rb', line 82

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