Sha256: 3d3fe7b6bc9c073584974cf57d5347078d1fed09a6463b86dfd06c2142ec5541

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

module Factory
  # Build actions for the model
  def self.build(model, &block)
    name = model.to_s.underscore
    
    define_method("#{name}_attributes", block)
    define_method("valid_#{name}_attributes") {|*args| valid_attributes_for(model, *args)}
    define_method("new_#{name}")              {|*args| new_record(model, *args)}
    define_method("create_#{name}")           {|*args| create_record(model, *args)}
  end
  
  # Get valid attributes for the model
  def valid_attributes_for(model, attributes = {})
    name = model.to_s.underscore
    send("#{name}_attributes", attributes)
    attributes.stringify_keys!
    attributes
  end
  
  # Build an unsaved record
  def new_record(model, *args)
    attributes = valid_attributes_for(model, *args)
    record = model.new(attributes)
    attributes.each {|attr, value| record.send("#{attr}=", value) if model.accessible_attributes && !model.accessible_attributes.include?(attr) || model.protected_attributes && model.protected_attributes.include?(attr)}
    record
  end
  
  # Build and save/reload a record
  def create_record(model, *args)
    record = new_record(model, *args)
    record.save!
    record.reload
    record
  end
  
  build Permission do |attributes|
    attributes.reverse_merge!(
      :controller => 'admin/users'
    )
  end
  
  build Role do |attributes|
    attributes.reverse_merge!(
      :name => 'developer'
    )
  end
  
  build RoleAssignment do |attributes|
    attributes[:role] = create_role unless attributes.include?(:role)
    attributes[:assignee] = create_user unless attributes.include?(:assignee)
  end
  
  build RolePermission do |attributes|
    attributes[:permission] = create_permission unless attributes.include?(:permission)
    attributes[:role] = create_role unless attributes.include?(:role)
  end
  
  build User do |attributes|
    attributes.reverse_merge!(
      :login => 'admin'
    )
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
has_roles-0.3.1 test/factory.rb
has_roles-0.3.0 test/factory.rb