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.



309
310
311
312
313
314
315
# File 'lib/active_hash/base.rb', line 309

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.



307
308
309
# File 'lib/active_hash/base.rb', line 307

def attributes
  @attributes
end

Class Method Details

.all(options = {}) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/active_hash/base.rb', line 75

def all(options={})
  if options.has_key?(:conditions)
    (@records || []).select do |record|
      options[:conditions].all? {|col, match| record[col] == match}
    end
  else
    @records || []
  end
end

.auto_assign_fields(array_of_hashes) ⇒ Object



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

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



270
271
272
# File 'lib/active_hash/base.rb', line 270

def base_class
  ActiveHash::Base
end

.configuration_for_custom_finder(finder_name) ⇒ Object



177
178
179
180
181
182
183
184
185
# File 'lib/active_hash/base.rb', line 177

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



85
86
87
# File 'lib/active_hash/base.rb', line 85

def count
  all.length
end

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



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

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

.create!(attributes = {}) ⇒ Object



69
70
71
72
73
# File 'lib/active_hash/base.rb', line 69

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

.data=(array_of_hashes) ⇒ Object



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

def data=(array_of_hashes)
  mark_dirty
  @records = nil
  write_inheritable_attribute(: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



236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/active_hash/base.rb', line 236

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



221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/active_hash/base.rb', line 221

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



189
190
191
192
193
194
195
# File 'lib/active_hash/base.rb', line 189

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



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

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



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

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



96
97
98
99
# File 'lib/active_hash/base.rb', line 96

def delete_all
  mark_dirty
  @records = []
end

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



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

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



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

def field_names
  @field_names ||= []
end

.fields(*args) ⇒ Object



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

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

.find(id, *args) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/active_hash/base.rb', line 101

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

.find_by_id(id) ⇒ Object



116
117
118
# File 'lib/active_hash/base.rb', line 116

def find_by_id(id)
  all.detect { |record| record.id == id.to_i }
end

.has_instance_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


293
294
295
# File 'lib/active_hash/base.rb', line 293

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

.has_singleton_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


299
300
301
# File 'lib/active_hash/base.rb', line 299

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

.insert(record) ⇒ Object



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

def insert(record)
  @records ||= []
  record.attributes[:id] ||= next_id
  mark_dirty
  @records << record
end

.mark_cleanObject



287
288
289
# File 'lib/active_hash/base.rb', line 287

def mark_clean
  self.dirty = false
end

.mark_dirtyObject



281
282
283
# File 'lib/active_hash/base.rb', line 281

def mark_dirty
  self.dirty = true
end

.method_missing(method_name, *args) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/active_hash/base.rb', line 158

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



51
52
53
54
55
56
57
58
# File 'lib/active_hash/base.rb', line 51

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

.reloadObject



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

def reload
  self.data = read_inheritable_attribute(:data)
  mark_clean
end

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

Returns:

  • (Boolean)


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

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



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

def the_meta_class
  class << self
    self
  end
end

.transactionObject



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

def transaction
  yield
rescue LocalJumpError => err
  raise err
rescue ActiveRecord::Rollback
end

.validate_field(field_name) ⇒ Object



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

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

Instance Method Details

#[](key) ⇒ Object



317
318
319
# File 'lib/active_hash/base.rb', line 317

def [](key)
  attributes[key]
end

#[]=(key, val) ⇒ Object



321
322
323
# File 'lib/active_hash/base.rb', line 321

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

#cache_keyObject



361
362
363
364
365
366
367
368
369
370
# File 'lib/active_hash/base.rb', line 361

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

#destroyed?Boolean

Returns:

  • (Boolean)


339
340
341
# File 'lib/active_hash/base.rb', line 339

def destroyed?
  false
end

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

Returns:

  • (Boolean)


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

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

#errorsObject



372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/active_hash/base.rb', line 372

def errors
  obj = Object.new

  def obj.[](key)
    []
  end

  def obj.full_messages()
    []
  end

  obj
end

#hashObject



357
358
359
# File 'lib/active_hash/base.rb', line 357

def hash
  id.hash
end

#idObject Also known as: quoted_id



325
326
327
# File 'lib/active_hash/base.rb', line 325

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

#id=(id) ⇒ Object



329
330
331
# File 'lib/active_hash/base.rb', line 329

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

#marked_for_destruction?Boolean

Returns:

  • (Boolean)


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

def marked_for_destruction?
  false
end

#new_record?Boolean

Returns:

  • (Boolean)


335
336
337
# File 'lib/active_hash/base.rb', line 335

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

#persisted?Boolean

Returns:

  • (Boolean)


343
344
345
# File 'lib/active_hash/base.rb', line 343

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

#readonly?Boolean

Returns:

  • (Boolean)


347
348
349
# File 'lib/active_hash/base.rb', line 347

def readonly?
  true
end

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



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

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

#to_paramObject



16
17
18
# File 'lib/active_hash/base.rb', line 16

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

#valid?Boolean

Returns:

  • (Boolean)


393
394
395
# File 'lib/active_hash/base.rb', line 393

def valid?
  true
end