Module: SelectableAttrRails::DbLoadable::InstanceMethods

Defined in:
lib/selectable_attr_rails/db_loadable.rb

Instance Method Summary collapse

Instance Method Details

#entriesObject



47
48
49
50
# File 'lib/selectable_attr_rails/db_loadable.rb', line 47

def entries
  update_entries if must_be_updated?
  @entries
end

#must_be_updated?Boolean

Returns:

  • (Boolean)


52
53
54
55
# File 'lib/selectable_attr_rails/db_loadable.rb', line 52

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

#update_entriesObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/selectable_attr_rails/db_loadable.rb', line 57

def update_entries
  unless @original_entries
    @original_entries = @entries.dup
    @original_entries.each do |entry|
      entry.extend(SelectableAttrRails::DbLoadable::Entry) unless respond_to?(:name_from_db)
    end
  end
  records = nil
  if @sql_to_update.respond_to?(:call)
    records = @sql_to_update.call
  else
    sql = @sql_to_update.gsub(/\:locale/, I18n.locale.to_s.inspect)
    records = ActiveRecord::Base.connection.select_rows(sql)
  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)
      entry.extend(SelectableAttrRails::DbLoadable::Entry)
      entry.name_from_db = 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