Class: ActiveHash::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Conversion
Defined in:
lib/active_hash/base.rb

Direct Known Subclasses

ActiveFile::Base

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



390
391
392
393
394
395
396
# File 'lib/active_hash/base.rb', line 390

def initialize(attributes = {})
  attributes.symbolize_keys!
  @attributes = attributes
  attributes.dup.each do |key, value|
    send "#{key}=", value
  end
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



388
389
390
# File 'lib/active_hash/base.rb', line 388

def attributes
  @attributes
end

Class Method Details

.add_to_record_index(entry) ⇒ Object



118
119
120
# File 'lib/active_hash/base.rb', line 118

def add_to_record_index(entry)
  record_index.merge!(entry)
end

.all(options = {}) ⇒ Object



145
146
147
148
149
150
151
# File 'lib/active_hash/base.rb', line 145

def all(options={})
  if options.has_key?(:conditions)
    where(options[:conditions])
  else
    @records || []
  end
end

.auto_assign_fields(array_of_hashes) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/active_hash/base.rb', line 333

def auto_assign_fields(array_of_hashes)
  (array_of_hashes || []).inject([]) do |array, row|
    row.symbolize_keys!
    row.keys.each do |key|
      unless key.to_s == "id"
        array << key
      end
    end
    array
  end.uniq.each do |key|
    field key
  end
end

.base_classObject

Needed for ActiveRecord polymorphic associations



350
351
352
# File 'lib/active_hash/base.rb', line 350

def base_class
  ActiveHash::Base
end

.cache_keyObject



34
35
36
37
38
39
40
# File 'lib/active_hash/base.rb', line 34

def cache_key
  if Object.const_defined?(:ActiveModel)
    model_name.cache_key
  else
    ActiveSupport::Inflector.tableize(self)
  end
end

.compute_type(type_name) ⇒ Object



56
57
58
# File 'lib/active_hash/base.rb', line 56

def compute_type(type_name)
  self
end

.configuration_for_custom_finder(finder_name) ⇒ Object



257
258
259
260
261
262
263
264
265
# File 'lib/active_hash/base.rb', line 257

def configuration_for_custom_finder(finder_name)
  if finder_name.to_s.match(/^find_(all_)?by_(.*?)(!)?$/) && !($1 && $3)
    {
      :all? => !!$1,
      :bang? => !!$3,
      :fields => $2.split('_and_')
    }
  end
end

.countObject



160
161
162
# File 'lib/active_hash/base.rb', line 160

def count
  all.length
end

.create(attributes = {}) ⇒ Object Also known as: add



130
131
132
133
134
135
# File 'lib/active_hash/base.rb', line 130

def create(attributes = {})
  record = new(attributes)
  record.save
  mark_dirty
  record
end

.create!(attributes = {}) ⇒ Object



139
140
141
142
143
# File 'lib/active_hash/base.rb', line 139

def create!(attributes = {})
  record = new(attributes)
  record.save!
  record
end

.dataObject



64
65
66
# File 'lib/active_hash/base.rb', line 64

def data
  _data
end

.data=(array_of_hashes) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/active_hash/base.rb', line 68

def data=(array_of_hashes)
  mark_dirty
  @records = nil
  reset_record_index
  self._data = array_of_hashes
  if array_of_hashes
    auto_assign_fields(array_of_hashes)
    array_of_hashes.each do |hash|
      insert new(hash)
    end
  end
end

.define_custom_find_all_method(field_name) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/active_hash/base.rb', line 316

def define_custom_find_all_method(field_name)
  method_name = :"find_all_by_#{field_name}"
  unless has_singleton_method?(method_name)
    the_meta_class.instance_eval do
      unless singleton_methods.include?(method_name)
        define_method(method_name) do |*args|
          options = args.extract_options!
          identifier = args[0]
          all.select { |record| record.send(field_name) == identifier }
        end
      end
    end
  end
end

.define_custom_find_method(field_name) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/active_hash/base.rb', line 301

def define_custom_find_method(field_name)
  method_name = :"find_by_#{field_name}"
  unless has_singleton_method?(method_name)
    the_meta_class.instance_eval do
      define_method(method_name) do |*args|
        options = args.extract_options!
        identifier = args[0]
        all.detect { |record| record.send(field_name) == identifier }
      end
    end
  end
end

.define_getter_method(field, default_value) ⇒ Object



269
270
271
272
273
274
275
# File 'lib/active_hash/base.rb', line 269

def define_getter_method(field, default_value)
  unless has_instance_method?(field)
    define_method(field) do
      attributes[field].nil? ? default_value : attributes[field]
    end
  end
end

.define_interrogator_method(field) ⇒ Object



290
291
292
293
294
295
296
297
# File 'lib/active_hash/base.rb', line 290

def define_interrogator_method(field)
  method_name = :"#{field}?"
  unless has_instance_method?(method_name)
    define_method(method_name) do
      send(field).present?
    end
  end
end

.define_setter_method(field) ⇒ Object



279
280
281
282
283
284
285
286
# File 'lib/active_hash/base.rb', line 279

def define_setter_method(field)
  method_name = "#{field}="
  unless has_instance_method?(method_name)
    define_method(method_name) do |new_val|
      attributes[field] = new_val
    end
  end
end

.delete_allObject



174
175
176
177
178
# File 'lib/active_hash/base.rb', line 174

def delete_all
  mark_dirty
  reset_record_index
  @records = []
end

.exists?(record) ⇒ Boolean

Returns:

  • (Boolean)


81
82
83
84
85
# File 'lib/active_hash/base.rb', line 81

def exists?(record)
  if record.id.present?
    record_index[record.id.to_s].present?
  end
end

.field(field_name, options = {}) ⇒ Object



209
210
211
212
213
214
215
216
217
218
# File 'lib/active_hash/base.rb', line 209

def field(field_name, options = {})
  validate_field(field_name)
  field_names << field_name

  define_getter_method(field_name, options[:default])
  define_setter_method(field_name)
  define_interrogator_method(field_name)
  define_custom_find_method(field_name)
  define_custom_find_all_method(field_name)
end

.field_namesObject



46
47
48
# File 'lib/active_hash/base.rb', line 46

def field_names
  @field_names ||= []
end

.fields(*args) ⇒ Object



202
203
204
205
206
207
# File 'lib/active_hash/base.rb', line 202

def fields(*args)
  options = args.extract_options!
  args.each do |field|
    field(field, options)
  end
end

.find(id, *args) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/active_hash/base.rb', line 180

def find(id, * args)
  case id
    when nil
      nil
    when :all
      all
    when Array
      id.map { |i| find(i) }
    else
      find_by_id(id) || begin
        raise RecordNotFound.new("Couldn't find #{name} with ID=#{id}")
      end
  end
end

.find_by_id(id) ⇒ Object



195
196
197
198
# File 'lib/active_hash/base.rb', line 195

def find_by_id(id)
  index = record_index[id.to_s]
  index and @records[index]
end

.has_instance_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


374
375
376
# File 'lib/active_hash/base.rb', line 374

def has_instance_method?(name)
  instance_methods.map { |method| method.to_sym }.include?(name)
end

.has_singleton_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


380
381
382
# File 'lib/active_hash/base.rb', line 380

def has_singleton_method?(name)
  singleton_methods.map { |method| method.to_sym }.include?(name)
end

.insert(record) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/active_hash/base.rb', line 87

def insert(record)
  @records ||= []
  record.attributes[:id] ||= next_id
  validate_unique_id(record) if dirty
  mark_dirty

  add_to_record_index({ record.id.to_s => @records.length })
  @records << record
end

.mark_cleanObject



368
369
370
# File 'lib/active_hash/base.rb', line 368

def mark_clean
  self.dirty = false
end

.mark_dirtyObject



362
363
364
# File 'lib/active_hash/base.rb', line 362

def mark_dirty
  self.dirty = true
end

.method_missing(method_name, *args) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/active_hash/base.rb', line 238

def method_missing(method_name, *args)
  return super unless respond_to? method_name

  config = configuration_for_custom_finder(method_name)
  attribute_pairs = config[:fields].zip(args)
  matches = all.select { |base| attribute_pairs.all? { |field, value| base.send(field).to_s == value.to_s } }

  if config[:all?]
    matches
  else
    result = matches.first
    if config[:bang?]
      result || raise(RecordNotFound, "Couldn\'t find #{name} with #{attribute_pairs.collect { |pair| "#{pair[0]} = #{pair[1]}" }.join(', ')}")
    else
      result
    end
  end
end

.next_idObject



97
98
99
100
101
102
103
104
# File 'lib/active_hash/base.rb', line 97

def next_id
  max_record = all.max { |a, b| a.id <=> b.id }
  if max_record.nil?
    1
  elsif max_record.id.is_a?(Numeric)
    max_record.id.succ
  end
end

.pluralize_table_namesObject



60
61
62
# File 'lib/active_hash/base.rb', line 60

def pluralize_table_names
  true
end

.primary_keyObject



42
43
44
# File 'lib/active_hash/base.rb', line 42

def primary_key
  "id"
end

.record_indexObject



106
107
108
# File 'lib/active_hash/base.rb', line 106

def record_index
  @record_index ||= {}
end

.reloadObject



354
355
356
357
358
# File 'lib/active_hash/base.rb', line 354

def reload
  reset_record_index
  self.data = _data
  mark_clean
end

.reset_record_indexObject



112
113
114
# File 'lib/active_hash/base.rb', line 112

def reset_record_index
  record_index.clear
end

.respond_to?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


228
229
230
231
232
233
234
235
236
# File 'lib/active_hash/base.rb', line 228

def respond_to?(method_name, include_private=false)
  super ||
    begin
      config = configuration_for_custom_finder(method_name)
      config && config[:fields].all? do |field|
        field_names.include?(field.to_sym) || field.to_sym == :id
      end
    end
end

.the_meta_classObject



50
51
52
53
54
# File 'lib/active_hash/base.rb', line 50

def the_meta_class
  class << self
    self
  end
end

.transactionObject



164
165
166
167
168
169
170
171
172
# File 'lib/active_hash/base.rb', line 164

def transaction
  yield
rescue LocalJumpError => err
  raise err
rescue StandardError => e
  unless Object.const_defined?(:ActiveRecord) && e.is_a?(ActiveRecord::Rollback)
    raise e
  end
end

.validate_field(field_name) ⇒ Object



220
221
222
223
224
# File 'lib/active_hash/base.rb', line 220

def validate_field(field_name)
  if [:attributes].include?(field_name.to_sym)
    raise ReservedFieldError.new("#{field_name} is a reserved field in ActiveHash.  Please use another name.")
  end
end

.validate_unique_id(record) ⇒ Object

Raises:



124
125
126
# File 'lib/active_hash/base.rb', line 124

def validate_unique_id(record)
  raise IdError.new("Duplicate ID found for record #{record.attributes.inspect}") if record_index.has_key?(record.id.to_s)
end

.where(options) ⇒ Object



153
154
155
156
157
158
# File 'lib/active_hash/base.rb', line 153

def where(options)
  return @records if options.nil?
  (@records || []).select do |record|
    options.all? { |col, match| record[col] == match }
  end
end

Instance Method Details

#[](key) ⇒ Object



398
399
400
# File 'lib/active_hash/base.rb', line 398

def [](key)
  attributes[key]
end

#[]=(key, val) ⇒ Object



402
403
404
# File 'lib/active_hash/base.rb', line 402

def []=(key, val)
  attributes[key] = val
end

#cache_keyObject



442
443
444
445
446
447
448
449
450
451
# File 'lib/active_hash/base.rb', line 442

def cache_key
  case
    when new_record?
      "#{self.class.cache_key}/new"
    when timestamp = self[:updated_at]
      "#{self.class.cache_key}/#{id}-#{timestamp.to_s(:number)}"
    else
      "#{self.class.cache_key}/#{id}"
  end
end

#destroyed?Boolean

Returns:

  • (Boolean)


420
421
422
# File 'lib/active_hash/base.rb', line 420

def destroyed?
  false
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


432
433
434
# File 'lib/active_hash/base.rb', line 432

def eql?(other)
  other.instance_of?(self.class) and not id.nil? and (id == other.id)
end

#errorsObject



453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/active_hash/base.rb', line 453

def errors
  obj = Object.new

  def obj.[](key)
    []
  end

  def obj.full_messages()
    []
  end

  obj
end

#hashObject



438
439
440
# File 'lib/active_hash/base.rb', line 438

def hash
  id.hash
end

#idObject Also known as: quoted_id



406
407
408
# File 'lib/active_hash/base.rb', line 406

def id
  attributes[:id] ? attributes[:id] : nil
end

#id=(id) ⇒ Object



410
411
412
# File 'lib/active_hash/base.rb', line 410

def id=(id)
  attributes[:id] = id
end

#marked_for_destruction?Boolean

Returns:

  • (Boolean)


480
481
482
# File 'lib/active_hash/base.rb', line 480

def marked_for_destruction?
  false
end

#new_record?Boolean

Returns:

  • (Boolean)


416
417
418
# File 'lib/active_hash/base.rb', line 416

def new_record?
  !self.class.all.include?(self)
end

#persisted?Boolean

Returns:

  • (Boolean)


424
425
426
# File 'lib/active_hash/base.rb', line 424

def persisted?
  self.class.all.map(&:id).include?(id)
end

#readonly?Boolean

Returns:

  • (Boolean)


428
429
430
# File 'lib/active_hash/base.rb', line 428

def readonly?
  true
end

#save(*args) ⇒ Object Also known as: save!



467
468
469
470
471
472
# File 'lib/active_hash/base.rb', line 467

def save(*args)
  unless self.class.exists?(self)
    self.class.insert(self)
  end
  true
end

#to_paramObject



27
28
29
# File 'lib/active_hash/base.rb', line 27

def to_param
  id.present? ? id.to_s : nil
end

#valid?Boolean

Returns:

  • (Boolean)


476
477
478
# File 'lib/active_hash/base.rb', line 476

def valid?
  true
end