Class: Ekylibre::Record::Base

Inherits:
ActiveRecord::Base
  • Object
show all
Extended by:
Enumerize
Includes:
ConditionalReadonly, ScopeIntrospection, Userstamp::Stampable, Userstamp::Stamper
Defined in:
lib/ekylibre/record/base.rb

Direct Known Subclasses

Account, AccountBalance, Activity, ActivityBudget, ActivityBudgetItem, ActivityDistribution, ActivityInspectionCalibrationNature, ActivityInspectionCalibrationScale, ActivityInspectionPointNature, ActivityProduction, ActivitySeason, ActivityTactic, Affair, Alert, AlertPhase, Analysis, AnalysisItem, Attachment, BankStatement, BankStatementItem, Call, CallMessage, Campaign, CapIslet, CapLandParcel, CapNeutralArea, CapStatement, Cash, CashSession, CashTransfer, Catalog, CatalogItem, Contract, ContractItem, Crumb, CultivableZone, CustomField, CustomFieldChoice, Dashboard, DebtTransfer, Delivery, DeliveryTool, Deposit, District, Document, DocumentTemplate, EconomicSituation, Entity, EntityAddress, EntityLink, Event, EventParticipation, FinancialYear, FinancialYearExchange, FixedAsset, FixedAssetDepreciation, Gap, GapItem, Georeading, Guide, GuideAnalysis, GuideAnalysisPoint, Identifier, Import, IncomingPayment, IncomingPaymentMode, Inspection, InspectionCalibration, InspectionPoint, Integration, Intervention, InterventionCosting, InterventionLabelling, InterventionParameter, InterventionParameterReading, InterventionParticipation, InterventionWorkingPeriod, Inventory, InventoryItem, Issue, Journal, JournalEntry, JournalEntryItem, Label, Listing, ListingNode, ListingNodeItem, Loan, LoanRepayment, ManureManagementPlan, ManureManagementPlanZone, MapLayer, NamingFormat, NamingFormatField, NetService, Notification, Observation, OutgoingPayment, OutgoingPaymentList, OutgoingPaymentMode, Parcel, ParcelItem, ParcelItemStoring, Payslip, PayslipNature, PlantCounting, PlantCountingItem, PlantDensityAbacus, PlantDensityAbacusItem, PostalZone, Preference, Prescription, Product, ProductEnjoyment, ProductLabelling, ProductLink, ProductLinkage, ProductLocalization, ProductMembership, ProductMovement, ProductNature, ProductNatureCategory, ProductNatureCategoryTaxation, ProductNatureVariant, ProductNatureVariantComponent, ProductNatureVariantReading, ProductOwnership, ProductPhase, ProductPopulation, ProductReading, ProjectBudget, Purchase, PurchaseItem, PurchaseNature, Regularization, Role, Sale, SaleItem, SaleNature, Sensor, Sequence, Subscription, SubscriptionNature, Supervision, SupervisionItem, SynchronizationOperation, TargetDistribution, Task, Tax, TaxDeclaration, TaxDeclarationItem, TaxDeclarationItemPart, Team, Token, Tracking, User

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Userstamp::Stampable

included

Methods included from Userstamp::Stamper

included

Class Attribute Details

.readonly_counterObject

Returns the value of attribute readonly_counter


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

def readonly_counter
  @readonly_counter
end

Class Method Details

.columns_definitionObject


115
116
117
# File 'lib/ekylibre/record/base.rb', line 115

def columns_definition
  Ekylibre::Schema.tables[table_name] || {}.with_indifferent_access
end

.customizable?Boolean

Returns:

  • (Boolean)

53
54
55
# File 'lib/ekylibre/record/base.rb', line 53

def self.customizable?
  respond_to?(:custom_fields)
end

.has_picture(options = {}) ⇒ Object


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/ekylibre/record/base.rb', line 97

def has_picture(options = {})
  default_options = {
    url: '/backend/:class/:id/picture/:style',
    path: ':tenant/:class/:attachment/:id_partition/:style.:extension',
    styles: {
      thumb: ['64x64>', :jpg],
      identity: ['180x180#', :jpg],
      contact: ['720x720#', :jpg]
    },
    convert_options: {
      thumb:    '-background white -gravity center -extent 64x64',
      identity: '-background white -gravity center -extent 180x180',
      contact: '-background white -gravity center -extent 720x720'
    }
  }
  has_attached_file :picture, default_options.deep_merge(options)
end

.nomenclature_reflectionsObject


119
120
121
122
123
124
125
126
# File 'lib/ekylibre/record/base.rb', line 119

def nomenclature_reflections
  @nomenclature_reflections ||= {}.with_indifferent_access
  if superclass.respond_to?(:nomenclature_reflections)
    superclass.nomenclature_reflections.merge(@nomenclature_reflections)
  else
    @nomenclature_reflections
  end
end

.refers_to(name, *args) ⇒ Object

Link to nomenclature


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/ekylibre/record/base.rb', line 129

def refers_to(name, *args)
  options = args.extract_options!
  scope = args.shift
  Rails.logger.warn 'Cannot support Proc scope' unless scope.nil?
  column = ["#{name}_tid".to_sym, "#{name}_name".to_sym, name].detect { |c| columns_definition[c] }
  options[:foreign_key] ||= column
  reflection = Nomen::Reflection.new(self, name, options)
  @nomenclature_reflections ||= {}.with_indifferent_access
  @nomenclature_reflections[reflection.name] = reflection
  enumerize reflection.foreign_key, in: reflection.all(reflection.scope),
                                    predicates: options[:predicates],
                                    i18n_scope: ["nomenclatures.#{reflection.nomenclature}.items"]

  if reflection.foreign_key != reflection.name
    define_method name do
      reflection.klass.find(self[reflection.foreign_key])
    end
  else
    define_method "#{name}_name" do
      item = reflection.klass.find(self[reflection.foreign_key])
      item ? item.name : nil
    end
  end

  define_method "human_#{name}_name" do
    item = reflection.klass.find(self[reflection.foreign_key])
    item ? item.human_name : nil
  end

  define_method "#{name}=" do |value|
    self[reflection.foreign_key] = value.is_a?(Nomen::Item) ? value.name : value
  end

  # Define a default scope "of_<name>"
  scope "of_#{name}".to_sym, proc { |*items|
    where(reflection.foreign_key => items.map { |i| reflection.klass.all(i) }.flatten.uniq)
  }

  define_method "of_#{name}?" do |item_or_name|
    item = item_or_name.is_a?(Nomen::Item) ? item_or_name : reflection.klass.find(item_or_name)
    self[reflection.foreign_key].present? && item >= self[reflection.foreign_key]
  end
end

Instance Method Details

#already_updated?Boolean

Returns:

  • (Boolean)

80
81
82
# File 'lib/ekylibre/record/base.rb', line 80

def already_updated?
  self.class.where(id: id, lock_version: lock_version).empty?
end

#check_if_destroyable?Boolean

Returns:

  • (Boolean)

35
36
37
38
39
# File 'lib/ekylibre/record/base.rb', line 35

def check_if_destroyable?
  unless destroyable?
    raise RecordNotDestroyable, "#{self.class.name} ID=#{id} is not destroyable"
  end
end

#check_if_updateable?Boolean

Returns:

  • (Boolean)

30
31
32
33
# File 'lib/ekylibre/record/base.rb', line 30

def check_if_updateable?
  true
  # raise RecordNotUpdateable unless self.updateable?
end

#customizable?Boolean

Returns:

  • (Boolean)

57
58
59
# File 'lib/ekylibre/record/base.rb', line 57

def customizable?
  self.class.customizable?
end

#customized?Boolean

Returns:

  • (Boolean)

61
62
63
# File 'lib/ekylibre/record/base.rb', line 61

def customized?
  customizable? && self.class.custom_fields.any?
end

#destroyable?Boolean

Returns:

  • (Boolean)

41
42
43
# File 'lib/ekylibre/record/base.rb', line 41

def destroyable?
  true
end

#editable?Boolean

Returns:

  • (Boolean)

49
50
51
# File 'lib/ekylibre/record/base.rb', line 49

def editable?
  updateable?
end

#human_attribute_name(*args) ⇒ Object


65
66
67
# File 'lib/ekylibre/record/base.rb', line 65

def human_attribute_name(*args)
  self.class.human_attribute_name(*args)
end

#old_recordObject

Returns a relation for the old record in DB


75
76
77
78
# File 'lib/ekylibre/record/base.rb', line 75

def old_record
  return nil if new_record?
  self.class.find_by(id: id)
end

#othersObject

Returns a relation for all other records


70
71
72
# File 'lib/ekylibre/record/base.rb', line 70

def others
  self.class.where.not(id: (id || -1))
end

#unsuppressObject


84
85
86
87
88
89
90
91
92
# File 'lib/ekylibre/record/base.rb', line 84

def unsuppress
  yield
rescue ActiveRecord::RecordInvalid => would_be_silently_dropped
  Rails.logger.info would_be_silently_dropped.inspect
  wont_be_dropped = Ekylibre::Record::RecordInvalid.new(would_be_silently_dropped.message,
                                                        would_be_silently_dropped.record)
  wont_be_dropped.set_backtrace(would_be_silently_dropped.backtrace)
  raise wont_be_dropped
end

#updateable?Boolean

Returns:

  • (Boolean)

45
46
47
# File 'lib/ekylibre/record/base.rb', line 45

def updateable?
  true
end