Module: SelectableAttrRails::DbLoadable::InstanceMethods

Defined in:
lib/selectable_attr_rails/db_loadable.rb

Instance Method Summary collapse

Instance Method Details

#entriesObject



19
20
21
22
# File 'lib/selectable_attr_rails/db_loadable.rb', line 19

def entries
  update_entries if must_be_updated?
  @entries
end

#must_be_updated?Boolean

Returns:

  • (Boolean)


24
25
26
27
# File 'lib/selectable_attr_rails/db_loadable.rb', line 24

def must_be_updated?
  return false if @update_timing == :never
  return true if @update_timing == :everytime
end

#update_entriesObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/selectable_attr_rails/db_loadable.rb', line 29

def update_entries
  unless @original_entries
    @original_entries = @entries.dup
    @original_entries.each do |entry|
      entry.extend(SelectableAttrRails::DbLoadable::Entry)
    end
  end
  records = nil
  if @sql_to_update.respond_to?(:call)
    records = @sql_to_update.call
  else
    @connection ||= ActiveRecord::Base.connection
    records = @connection.select_rows(@sql_to_update)
  end
  
  new_entries = []
  records.each do |r|
    if entry = @original_entries.detect{|entry| entry.id == r.first}
      entry.name_from_db = r.last unless r.last.blank?
      new_entries << entry
    else
      entry = SelectableAttr::Enum::Entry.new(self, r.first, "entry_#{r.first}".to_sym, r.last)
      new_entries << entry
    end
  end
  @original_entries.each do |entry|
    unless new_entries.include?(entry)
      entry.name_from_db = nil
      new_entries << entry if entry.defined_in_code
    end
  end
  @entries = new_entries
end