Module: ConsoleUpdate::SingletonMethods

Defined in:
lib/console_update.rb

Instance Method Summary collapse

Instance Method Details

#console_update(records, options = {}) ⇒ Object

This is the main method for updating records. All other update-like methods pass their options through here.

Options:

:only

Only edit these attributes.

:except

Edit default attributes except for these.

Examples:

records = Url.all :limit=>10
Url.console_update records
Url.console_update records, :only=>%w{column1}
Url.console_update records, :except=>%w{column1}


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/console_update.rb', line 59

def console_update(records, options={})
  begin
    editable_attributes_array = records.map {|e| e.console_editable_attributes(options) }
    editable_string = filter.hashes_to_string(editable_attributes_array)
    new_attributes_array = editor_update(editable_string)
    records.each do |record|
      if (record_attributes = new_attributes_array.detect {|e| e['id'] == record.id })
        record.update_console_attributes(record_attributes)
      end
    end
  rescue ConsoleUpdate::Filter::AbstractMethodError
    puts "Undefined filter method for #{ConsoleUpdate::filter} filter"
  rescue StandardError=>e
    puts "Some record(s) didn't update because of this error: #{e}"
  ensure
    #this attribute should only last duration of method
    reset_editable_attribute_names
  end
end

#editable_attribute_names(options = {}) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/console_update.rb', line 99

def editable_attribute_names(options={})
  unless @editable_attribute_names
    @editable_attribute_names = if options[:only]
      options[:only]
    elsif options[:except]
      default_editable_attributes - options[:except]
    else
      default_editable_attributes
    end
  end
  @editable_attribute_names
end

#editor_update(string) ⇒ Object

:stopdoc:



89
90
91
92
93
94
95
# File 'lib/console_update.rb', line 89

def editor_update(string) 
  tmpfile = Tempfile.new('console_update')
  File.open(tmpfile.path, 'w+') {|f| f.write(string)}
  system(console_editor, tmpfile.path)
  updated_string = File.read(tmpfile.path)
  filter.string_to_hashes(updated_string)
end

#filterObject

:nodoc:



79
80
81
# File 'lib/console_update.rb', line 79

def filter #:nodoc:
  @filter ||= ConsoleUpdate::Filter.new(ConsoleUpdate.filter)
end

#find_and_console_update(id, options = {}) ⇒ Object

Console updates a record given an id.



84
85
86
# File 'lib/console_update.rb', line 84

def find_and_console_update(id, options={})
  console_update([find(id)], options)
end

#reset_editable_attribute_namesObject



97
# File 'lib/console_update.rb', line 97

def reset_editable_attribute_names; @editable_attribute_names = nil ; end