Class: SugarCRM::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/sugarcrm/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}, &block) ⇒ Base

Creates an instance of a Module Class, i.e. Account, User, Contact, etc.



134
135
136
137
138
139
140
141
142
143
144
# File 'lib/sugarcrm/base.rb', line 134

def initialize(attributes={}, &block)
  attributes.delete('id')
  @errors = {}
  @modified_attributes = {}
  merge_attributes(attributes.with_indifferent_access)
  clear_association_cache
  define_attribute_methods
  define_association_methods
  typecast_attributes
  self
end

Instance Attribute Details

#associationsObject

Returns the value of attribute associations.



23
24
25
# File 'lib/sugarcrm/base.rb', line 23

def associations
  @associations
end

#attributesObject

Contains a list of attributes



21
22
23
# File 'lib/sugarcrm/base.rb', line 21

def attributes
  @attributes
end

#debugObject

Returns the value of attribute debug.



24
25
26
# File 'lib/sugarcrm/base.rb', line 24

def debug
  @debug
end

#errorsObject

Returns the value of attribute errors.



25
26
27
# File 'lib/sugarcrm/base.rb', line 25

def errors
  @errors
end

#modified_attributesObject

Returns the value of attribute modified_attributes.



22
23
24
# File 'lib/sugarcrm/base.rb', line 22

def modified_attributes
  @modified_attributes
end

Class Method Details

.all(*args, &block) ⇒ Object

This is an alias for find(:all). You can pass in all the same arguments to this method as you can to find(:all)



95
96
97
# File 'lib/sugarcrm/base.rb', line 95

def all(*args, &block)
  find(:all, *args, &block)
end

.connectionObject

return the connection to the correct SugarCRM server (there can be several)



68
69
70
# File 'lib/sugarcrm/base.rb', line 68

def connection
  self.session.connection
end

.count(options = {}) ⇒ Object

return the number of records satifsying the options note: the REST API has a bug (documented with Sugar as bug 43339) where passing custom attributes in the options will result in the options being ignored and ‘0’ being returned, regardless of the existence of records satisfying the options

Raises:



75
76
77
78
79
# File 'lib/sugarcrm/base.rb', line 75

def count(options={})
  raise InvalidAttribute, 'Conditions on custom attributes are not supported due to REST API bug' if contains_custom_attribute(options[:conditions])
  query = query_from_options(options)
  connection.get_entries_count(self._module.name, query, options)['result_count'].to_i
end

.create(attributes = nil, &block) ⇒ Object

Creates an object (or multiple objects) and saves it to SugarCRM if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

The attributes parameter can be either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.

Examples

# Create a single new object
User.create(:first_name => 'Jamie')

# Create an Array of new objects
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(:first_name => 'Jamie') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
  u.is_admin = false
end


121
122
123
124
125
126
127
128
129
130
# File 'lib/sugarcrm/base.rb', line 121

def create(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, &block) }
  else
    object = new(attributes)
    yield(object) if block_given?
    object.save
    object
  end
end

.find(*args, &block) ⇒ Object



28
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
62
63
64
65
# File 'lib/sugarcrm/base.rb', line 28

def find(*args, &block)
  options = args.extract_options!
  # add default sorting date (necessary for first and last methods to work)
  # most modules (Contacts, Accounts, etc.) use 'date_entered' to store when the record was created
  # other modules (e.g. EmailAddresses) use 'date_created'
  # Here, we account for this discrepancy...
  self.new # make sure the fields are loaded from SugarCRM so method_defined? will work properly
  if self.method_defined? :date_entered
    sort_criteria = 'date_entered'
  elsif self.method_defined? :date_created
    sort_criteria = 'date_created'
  # Added date_modified because TeamSets doesn't have a date_created or date_entered field.  
  # There's no test for this because it's Pro and above only.
  # Hope this doesn't break anything!
  elsif self.method_defined? :date_modified
    sort_criteria = 'date_modified'
  else
    raise InvalidAttribute, "Unable to determine record creation date for sorting criteria: expected date_entered, date_created, or date_modified attribute to be present"
  end
  options = {:order_by => sort_criteria}.merge(options)
  validate_find_options(options)

  case args.first
    when :first
      find_initial(options)
    when :last
      begin
        options[:order_by] = reverse_order_clause(options[:order_by].to_s)
      rescue Exception => e
        raise
      end
      find_initial(options)
    when :all
      Array.wrap(find_every(options, &block)).compact
    else
      find_from_ids(args, options, &block)
  end
end

.first(*args, &block) ⇒ Object

A convenience wrapper for find(:first, *args). You can pass in all the same arguments to this method as you can to find(:first).



83
84
85
# File 'lib/sugarcrm/base.rb', line 83

def first(*args, &block)
  find(:first, *args, &block)
end

.last(*args, &block) ⇒ Object

A convenience wrapper for find(:last, *args). You can pass in all the same arguments to this method as you can to find(:last).



89
90
91
# File 'lib/sugarcrm/base.rb', line 89

def last(*args, &block)
  find(:last, *args, &block)
end

Instance Method Details

#==(comparison_object) ⇒ Object Also known as: eql?

Returns true if comparison_object is the same exact object, or comparison_object is of the same type and self has an ID and it is equal to comparison_object.id.

Note that new records are different from any other record by definition, unless the other record is the receiver itself. Besides, if you fetch existing records with select and leave the ID out, you’re on your own, this predicate will return false.

Note also that destroying a record preserves its ID in the model instance, so deleted models are still comparable.



215
216
217
218
219
# File 'lib/sugarcrm/base.rb', line 215

def ==(comparison_object)
    comparison_object.instance_of?(self.class) &&
    id.present? &&
    comparison_object.id == id
end

#association_methods_generated?Boolean

Returns:

  • (Boolean)


271
272
273
# File 'lib/sugarcrm/base.rb', line 271

def association_methods_generated?
  self.class.association_methods_generated
end

#attribute_methods_generated?Boolean

Returns:

  • (Boolean)


267
268
269
# File 'lib/sugarcrm/base.rb', line 267

def attribute_methods_generated?
  self.class.attribute_methods_generated
end

#blank?Boolean Also known as: empty?

Returns:

  • (Boolean)


201
202
203
# File 'lib/sugarcrm/base.rb', line 201

def blank?
  @attributes.empty?
end

#deleteObject Also known as: destroy



182
183
184
185
186
187
188
# File 'lib/sugarcrm/base.rb', line 182

def delete
  return false if id.blank?
  params          = {}
  params[:id]     = serialize_id
  params[:deleted]= {:name => "deleted", :value => "1"}
  @attributes[:deleted] = (self.class.connection.set_entry(self.class._module.name, params).class == Hash)
end

#hashObject

Delegates to id in order to allow two records of the same type and id to work with something like:

[ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]


259
260
261
# File 'lib/sugarcrm/base.rb', line 259

def hash
  id.hash
end

#inspectObject



146
147
148
# File 'lib/sugarcrm/base.rb', line 146

def inspect
  self
end

#is_a?(klass) ⇒ Boolean Also known as: kind_of?, ===

Returns:

  • (Boolean)


283
284
285
# File 'lib/sugarcrm/base.rb', line 283

def is_a?(klass)
  superclasses.include? klass
end

#persisted?Boolean

Returns if the record is persisted, i.e. it’s not a new record and it was not destroyed

Returns:

  • (Boolean)


192
193
194
# File 'lib/sugarcrm/base.rb', line 192

def persisted?
  !(new_record? || destroyed?)
end

#pretty_print(pp) ⇒ Object



263
264
265
# File 'lib/sugarcrm/base.rb', line 263

def pretty_print(pp)
  pp.text self.inspect.to_s, 0
end

#reload!Object

Reloads the record from SugarCRM



197
198
199
# File 'lib/sugarcrm/base.rb', line 197

def reload!
  self.attributes = self.class.find(self.id).attributes
end

#save(opts = {}) ⇒ Object

Saves the current object, checks that required fields are present. returns true or false



160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/sugarcrm/base.rb', line 160

def save(opts={})
  options = { :validate => true }.merge(opts)
  return false if !(new_record? || changed?)
  if options[:validate]
    return false if !valid?
  end
  begin
    save!(options)
  rescue
    return false
  end
  true
end

#save!(opts = {}) ⇒ Object

Saves the current object, and any modified associations. Raises an exceptions if save fails for any reason.



176
177
178
179
180
# File 'lib/sugarcrm/base.rb', line 176

def save!(opts={})
  save_modified_attributes!(opts)
  save_modified_associations!
  true
end

#to_keyObject



275
276
277
# File 'lib/sugarcrm/base.rb', line 275

def to_key
  new_record? ? nil : [ id ]
end

#to_paramObject



279
280
281
# File 'lib/sugarcrm/base.rb', line 279

def to_param
  id.to_s
end

#to_sObject



150
151
152
153
154
155
156
# File 'lib/sugarcrm/base.rb', line 150

def to_s
  attrs = []
  @attributes.keys.sort.each do |k|
    attrs << "#{k}: #{attribute_for_inspect(k)}"
  end
  "#<#{self.class} #{attrs.join(", ")}>"
end

#update_attribute(name, value) ⇒ Object



227
228
229
230
231
232
233
234
# File 'lib/sugarcrm/base.rb', line 227

def update_attribute(name, value)
  begin
    update_attribute!(name, value)
  rescue
    return false
  end
  true
end

#update_attribute!(name, value) ⇒ Object



222
223
224
225
# File 'lib/sugarcrm/base.rb', line 222

def update_attribute!(name, value)
  self.send("#{name}=".to_sym, value)
  self.save!
end

#update_attributes(attributes) ⇒ Object



243
244
245
246
247
248
249
250
# File 'lib/sugarcrm/base.rb', line 243

def update_attributes(attributes)
  begin
    update_attributes!(attributes)
  rescue
    return false
  end
  true
end

#update_attributes!(attributes) ⇒ Object



236
237
238
239
240
241
# File 'lib/sugarcrm/base.rb', line 236

def update_attributes!(attributes)
  attributes.each do |name, value|
    self.send("#{name}=".to_sym, value)
  end
  self.save!
end

#urlObject

Returns the URL (in string format) where the module instance is available in CRM



253
254
255
# File 'lib/sugarcrm/base.rb', line 253

def url
  "#{SugarCRM.session.config[:base_url]}/index.php?module=#{self.class._module.name}&action=DetailView&record=#{self.id}"
end