Class: Tkellem::TkellemBot::CRUDCommand

Inherits:
Command
  • Object
show all
Defined in:
lib/tkellem/tkellem_bot.rb

Direct Known Subclasses

ListenCommand, UserCommand

Instance Attribute Summary

Attributes inherited from Command

#args, #bouncer, #conn, #options, #opts

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Command

admin_only?, admin_option, admin_user?, build_options, #initialize, option, register, resources, #respond, run, #show_help, #user

Constructor Details

This class inherits a constructor from Tkellem::TkellemBot::Command

Class Method Details

.register_crud(name, model) ⇒ Object



143
144
145
146
147
148
# File 'lib/tkellem/tkellem_bot.rb', line 143

def self.register_crud(name, model)
  register(name)
  cattr_accessor :model
  self.model = model
  option('remove', '--remove', '-r', "delete the specified record")
end

Instance Method Details

#executeObject



198
199
200
201
202
203
204
205
206
207
208
# File 'lib/tkellem/tkellem_bot.rb', line 198

def execute
  if opts['remove'] && args.length == 1
    remove
  elsif args.length == 0
    list
  elsif args.length == 1
    modify
  else
    raise Command::ArgumentError, "Unknown sub-command"
  end
end

#find_attributesObject



154
155
156
# File 'lib/tkellem/tkellem_bot.rb', line 154

def find_attributes
  attributes
end

#listObject



158
159
160
161
# File 'lib/tkellem/tkellem_bot.rb', line 158

def list
  r "All #{self.class.name.pluralize}:"
  model.all.each { |m| r "    #{show(m)}" }
end

#modifyObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/tkellem/tkellem_bot.rb', line 163

def modify
  instance = model.where(find_attributes).first
  new_record = false
  if instance
    instance.attributes = attributes
    if instance.changed?
      instance.save
    else
      respond "   #{show(instance)}"
      return
    end
  else
    new_record = true
    instance = model.create(attributes)
  end
  if instance.errors.any?
    respond "Error:"
    instance.errors.full_messages.each { |m| respond "    #{m}" }
    respond "    #{show(instance)}"
  else
    respond(new_record ? "created:" : "updated:")
    respond "    #{show(instance)}"
  end
end

#removeObject



188
189
190
191
192
193
194
195
196
# File 'lib/tkellem/tkellem_bot.rb', line 188

def remove
  instance = model.where(find_attributes).first
  if instance
    instance.destroy
    respond "Removed #{show(instance)}"
  else
    respond "Not found"
  end
end

#show(m) ⇒ Object



150
151
152
# File 'lib/tkellem/tkellem_bot.rb', line 150

def show(m)
  m.to_s
end