Skip to content

Instantly share code, notes, and snippets.

@babelian
Created May 20, 2011 12:23
Show Gist options
  • Save babelian/982801 to your computer and use it in GitHub Desktop.
Save babelian/982801 to your computer and use it in GitHub Desktop.
dynanic mass assign
class Project < ActiveRecord::Base
class << self
def always_attributes
%w{attributes anybody can edit}
end
def draft_attributes
%w{available only while project is being written}
end
def live_attributes
%w{available only to admins post launch}
end
end
def editable_attributes
#always attributes
a = self.class.always_attributes
#stateful attributes
if self.class.owner_editable_states.include?(state)
a += self.class.draft_attributes
end
#authorization attributes
if User.can('super')
a += self.class.draft_attributes+self.class.manager_attributes+self.class.live_attributes
elsif User.can('edit_live', self)
a += self.class.draft_attributes+self.class.live_attributes
a += (config[:monitor_editable_attributes] || []) #serialized config for each project
else
a += (config[:owner_editable_attributes] || [])
end
#attributes still at default can always be set
a += ['name'] if name.blank?
a += ['target_raised target_raised_cents'] if target_raised_cents == 0
a += a.select{|k| k =~ /_at$/ }.collect{|k| k.sub(/_at/, '_on') }
#sort and return
a = a.collect(&:to_s).sort.uniq
a -= self.class.active_authorizer.to_a #remove always protected attributes like 'id', 'state'
ActiveModel::MassAssignmentSecurity::WhiteList.new(a)
end
protected
def mass_assignment_authorizer
if User.current_user
editable_attributes
else
super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment