Class: AdminAssistant::AssociationTarget

Inherits:
Object
  • Object
show all
Defined in:
lib/admin_assistant/association_target.rb

Instance Method Summary collapse

Constructor Details

#initialize(associated_class) ⇒ AssociationTarget

Returns a new instance of AssociationTarget.



3
4
5
# File 'lib/admin_assistant/association_target.rb', line 3

def initialize(associated_class)
  @associated_class = associated_class
end

Instance Method Details

#assoc_value(assoc_value) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/admin_assistant/association_target.rb', line 7

def assoc_value(assoc_value)
  if assoc_value.respond_to?(:name_for_admin_assistant)
    assoc_value.name_for_admin_assistant
  elsif assoc_value && default_name_method
    assoc_value.send default_name_method
  end
end

#default_name_methodObject



15
16
17
18
19
# File 'lib/admin_assistant/association_target.rb', line 15

def default_name_method
  [:name, :title, :login, :username].detect { |m|
    @associated_class.columns.any? { |column| column.name.to_s == m.to_s }
  }
end

#nameObject



21
22
23
# File 'lib/admin_assistant/association_target.rb', line 21

def name
  @associated_class.name.gsub(/([A-Z])/, ' \1')[1..-1].downcase
end

#options_for_selectObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/admin_assistant/association_target.rb', line 25

def options_for_select
  records = @associated_class.find(:all)
  name_method = default_name_method
  if name_method.nil? and
     records.first.respond_to?(:name_for_admin_assistant)
    name_method = :name_for_admin_assistant
  end
  sort_value_method = nil
  if records.first.respond_to?(:sort_value_for_admin_assistant)
    sort_value_method = :sort_value_for_admin_assistant
  else
    sort_value_method = name_method
  end
  if sort_value_method
    records = records.sort_by { |model| model.send(sort_value_method) }
  end
  if name_method
    records.map { |model| [model.send(name_method), model.id] }
  else
    records.map &:id
  end
end